检查List中是否存在具有特定值的对象[重复]

问题描述 投票:0回答:3

我正在尝试检查列表中是否存在特定对象。我有 ListA,其中包含所有元素,并且我有一个字符串,它可能属于也可能不属于 List A 中一个对象的 id。

我知道以下几点:

如果列表中存在该元素,则

List<T>.Contains(T)
返回 true。问题:我必须搜索特定元素。

如果

List<T>.Find(Predicate<T>)
在列表中找到具有谓词的元素,则返回一个对象。问题:这给了我一个对象,但我想要 true 或 false。

现在我想出了这个:

if (ListA.Contains(ListA.Find(a => a.Id == stringID)) ==true)
...做很酷的事

这是最好的解决方案吗?我觉得有点奇怪。

c# list find contains
3个回答
12
投票

您可以使用

Any()

来自 Linq 的

Any()
,查找列表中的任何元素是否满足给定 条件与否,如果满足则返回
true

if (ListA.Any(a => a.Id == stringID))
{
    // Your logic goes here
}

MSDN:可枚举。任何方法


3
投票

使用 .Any 是最好的选择:MSDN

if(ListA.Any(a => a.Id == stringID))
{
    //You have your value.
} 

2
投票

为此使用

Any

if (ListA.Any(item => item.id == yourId))
{
   ...
}
© www.soinside.com 2019 - 2024. All rights reserved.