如何在列表中找到项目(T) [英] How do I find an item in a list(of T)

查看:83
本文介绍了如何在列表中找到项目(T)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试了解如何检查列表中的重复名称(T)。我的名字还没有在列表中,在我把它放入列表之前,我需要在将新信息添加到列表之前检查重复项。



以下是Griff昨天帮我解决的一些代码。



昏暗的联系方式新列表(联系方式)()

Dim newContact As新联系人()



newContact.FirstName =joe

newContact.LastName =smith

newContact.PhoneNumber =234345435

newContact.Birthday = Date.Now.AddYears(-20)

contacts.Add(newContact)



我想知道的是,现有类中的姓氏是否与我尚未实例化的内存中的姓氏相匹配?



我感谢任何帮助,

谢谢



我尝试过的事情:



我已经尝试了上面的代码而且我一直在搜索n等了几天。大多数答案是关于使用谓词,我也不知道如何使用它。所以我想知道在没有它的情况下如何做到这一点。

Hello, I'm trying to understand how to check duplicates names in a list(of T). I have a name that's not in the list yet, and before I put it in the list, I need to check for duplicates before adding the new information to the list.

Here's some code that Griff helped me out with yesterday.

Dim contacts As New List(Of Contact)()
Dim newContact As New Contact()

newContact.FirstName = "joe"
newContact.LastName = "smith"
newContact.PhoneNumber = "234345435"
newContact.Birthday = Date.Now.AddYears(-20)
contacts.Add(newContact)

What I want to know is, does the last name in the existing class match the the last name that's in memory that I haven't instantiated yet?

I appreciate any help at all,
thanks

What I have tried:

I've tried the above code and I've been searching the net for days. Most of the answers are about using a predicate and I don't know how to use that either. So I would like to know how to do it without it first if possible.

推荐答案

尝试以下方法:

Try the following:
If Not contacts.Any(Function(obj) obj.LastName = "smith") Then
    Dim newContact As New Contact()
    newContact.FirstName = "joe"
    newContact.LastName = "smith"
    newContact.PhoneNumber = "234345435"
    newContact.Birthday = Date.Now.AddYears(-20)
    contacts.Add(newContact)
End If



任何之后括号中的位是 Lambda表达式 [ ^ ]

它本质上是说 - 这是一个函数,它将带一个参数 obj 并带有 obj 我们想查看 LastName 属性并将其与文本smith(您可能希望在进行比较之前转换为小写或大写字母。)



编译器知道 LastName 可以是 obj 的属性,因为我们使用的是 contacts.Any ,它知道联系人列表 联系。我们正在使用 .Any 因为我们实际上并不需要匹配列表,我们只需要知道如果匹配。

并注意因为 .Any 将返回 True 如果找到匹配


The bit in brackets after Any is a Lambda expression[^]
It's essentially saying - here is a Function that is going to take a parameter obj and with obj we want to look at the LastName property and compare it to the text "smith"(you would probably want to convert to lowercase or capitals before doing the comparison).

The compiler knows that LastName can be a property of obj because we are using contacts.Any and it knows that contacts is a List of Contact. We are using .Any because we don't actually need a list of matches, we just need to know if there is a match.
And note the Not because the .Any will return True if it does find a match


这篇关于如何在列表中找到项目(T)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆