Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查数组是否包含具有Linq/C的属性id#_C# - Fatal编程技术网

C# 检查数组是否包含具有Linq/C的属性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。这些对象具有
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);