检查列表中是否存在具有特定值的对象
Check if object with specific value exists in List
我正在尝试检查列表中是否存在特定对象。我有 ListA,它包含所有元素,我有一个字符串,它可能属于也可能不属于列表 A 中一个对象的 ID。
我知道以下内容:
List<T>.Contains(T)
returns 如果元素存在于列表中则为真。问题:我必须搜索特定元素。
List<T>.Find(Predicate<T>)
returns 如果在 List 中找到具有谓词的元素,则对象。问题:这给了我一个对象,但我想要 true 或 false。
现在我想到了这个:
if (ListA.Contains(ListA.Find(a => a.Id == stringID)) ==true)
...做些酷事
这是最好的解决方案吗?我觉得有点奇怪。
您可以使用Any()
,
Any()
from Linq, finds whether any element in list satisfies given
condition or not, If satisfies then return true
if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;
}
为此使用 Any
。
if (ListA.Any(item => item.id == yourId))
{
...
}
使用 .Any 是最佳选择:MSDN
if(ListA.Any(a => a.Id == stringID))
{
//You have your value.
}
我正在尝试检查列表中是否存在特定对象。我有 ListA,它包含所有元素,我有一个字符串,它可能属于也可能不属于列表 A 中一个对象的 ID。
我知道以下内容:
List<T>.Contains(T)
returns 如果元素存在于列表中则为真。问题:我必须搜索特定元素。
List<T>.Find(Predicate<T>)
returns 如果在 List 中找到具有谓词的元素,则对象。问题:这给了我一个对象,但我想要 true 或 false。
现在我想到了这个:
if (ListA.Contains(ListA.Find(a => a.Id == stringID)) ==true)
...做些酷事
这是最好的解决方案吗?我觉得有点奇怪。
您可以使用Any()
,
Any()
from Linq, finds whether any element in list satisfies given condition or not, If satisfies then returntrue
if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;
}
为此使用 Any
。
if (ListA.Any(item => item.id == yourId))
{
...
}
使用 .Any 是最佳选择:MSDN
if(ListA.Any(a => a.Id == stringID))
{
//You have your value.
}