2013-03-06 30 views
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列表。 我想要做的就是找到一个TestClass包含与ID0

List<TestClass> TestList = RetrieveAllTestLists(); 
//Pseudocode: 
// 
// Find all TestClass in TestList that contain a Stuff with ID == 0; 

的我已经试过这任何Stuff但它没有工作:

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

谁能给我解释一下我做错了什么?

回答

5

您可以使用Any

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

Basicaly Where会选择满足条件的所有行(那些返回true),但在这个地方,你有另一个Where。如果存在满足给定条件的任何行,则返回。

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

任何()是指至少一个元件或IEnumerable的,在参数给出的谓词返回true