Reputation: 2305
I'm a bit confused on how this works.
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;}
}
So each TestClass
has a list of Stuff
in them.
What I want to do is find a TestClass
that contains any Stuff
with an ID
of 0
List<TestClass> TestList = RetrieveAllTestLists();
//Pseudocode:
//
// Find all TestClass in TestList that contain a Stuff with ID == 0;
I've tried this but it didn't work:
List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Where(y=> y.ID == 0)).ToList();
Can anyone explain to me what I did wrong?
Upvotes: 3
Views: 86
Reputation: 7870
List<TestClass> TestList = RetrieveAllTestLists().Where(x=> x.StuffList.Any(y=> y.ID == 0)).ToList();
Any() means that at least for one element or the IEnumerable, the predicate given in parameter returns true
Upvotes: 0
Reputation: 27594
You can use Any
:
List<TestClass> TestList = RetrieveAllTestLists().
Where(x => x.StuffList.Any(y=> y.ID == 0)).ToList();
Basicaly Where
will select all rows which satisfies condition (those returning true
), but in this place you have another Where
. Any
will return true
if there were any row fulfilling given condition.
Upvotes: 5