C# 检查数组是否包含具有Linq/C的属性id#
目前,我在数组中循环并检查是否有任何对象包含特定id。这些对象具有C# 检查数组是否包含具有Linq/C的属性id#,c#,C#,目前,我在数组中循环并检查是否有任何对象包含特定id。这些对象具有id属性 public class MyObj { public int Id {get; set;} } 所以当检查锁定状态时,我选择这个代码 bool IsUnlocked(int targetId) { bool isUnlocked = false; for (int i = 0; i < myObjs.Length; i++) // loop trough the objects { MyOb
id
属性
public class MyObj
{
public int Id {get; set;}
}
所以当检查锁定状态时,我选择这个代码
bool IsUnlocked(int targetId) {
bool isUnlocked = false;
for (int i = 0; i < myObjs.Length; i++) // loop trough the objects
{
MyObj current = myObjs[i];
if (current.Id == targetId) // a match
{
isUnlocked = true;
break;
}
}
return isUnlocked;
}
但这是一个错误的语法。我是否需要设置类似的内容
myObjs.First(current => current.Id == targetId);
Contains
不采用委托类型,因此将current=>current.Id==targetId的行为传递给它将不会编译
至于myObjs.First(current=>current.Id==targetId)
,这将返回满足所提供谓词的第一个对象,而不是返回一个bool
,指示是否有任何项满足所提供谓词
解决方案是使用Any
扩展方法
bool isUnlocked = myObjs.Any(current => current.Id == targetId);
数组中还有一个专用的方法
类-:
bool isUnlocked = myObjs.Any(current => current.Id == targetId);
isUnlocked = Array.Exists(myObjs, elem => elem.Id == targetId);