在列表项中查找一个列表项

3
我有点困惑这是如何工作的。
class TestClass
{
    public int ID {get;set;}
    public List<Stuff> StuffList {get; set;}
}
class Stuff
{
    public int ID {get;set;}
    public string Description {get;set;}
}

所以每个TestClass都有一个Stuff列表。 我想要做的是找到一个包含任何ID0StuffTestClass
List<TestClass> TestList = RetrieveAllTestLists();
//Pseudocode:
//
// Find all TestClass in TestList that contain a Stuff with ID == 0;

我尝试了这个方法,但它没有起作用:
List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Where(y=> y.ID == 0)).ToList();

有人可以解释一下我做错了什么吗?

2个回答

5
你可以使用Any:
List<TestClass> TestList = RetrieveAllTestLists().
                           Where(x => x.StuffList.Any(y=> y.ID == 0)).ToList();

基本上,Where 会选择所有满足条件的行(返回 true 的行),但在这个位置你有另一个 Where。如果存在任何满足给定条件的行,则 Any 将返回 true


0
List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Any(y=> y.ID == 0)).ToList();

Any()

的意思是:对于IEnumerable中的至少一个元素,给定的谓词返回true。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接