检查对象列表是否包含具有特定值的属性

假设我有以下代码:

class SampleClass
{
public int Id {get; set;}
public string Name {get; set;}
}
List<SampleClass> myList = new List<SampleClass>();
//list is filled with objects
...
string nameToExtract = "test";

所以我的问题是,我可以使用哪个 List 函数来从 myList中提取只有 Name 属性与我的 nameToExtract字符串匹配的对象。

如果这个问题真的很简单/明显,我提前道歉。

202660 次浏览

You can use the Enumerable.Where extension method:

var matches = myList.Where(p => p.Name == nameToExtract);

Returns an IEnumerable<SampleClass>. Assuming you want a filtered List, simply call .ToList() on the above.


By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:

var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));

See also

using System.Linq;
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

myList.Where(item=>item.Name == nameToExtract)

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);
list.Any(x=>x.name==string)

Could check any name prop included by list.