Linq: Is there a way to search a list of objects for values that match a condition?
I have 3 types of objects, TypeA, TypeB, TypeC. TypeA has a list of TypeB and TypeB has a list of TypeC and TypeC has some variables that I want to keep track of
Class TypeA
{
List<TypeB> MyListOfTypeB;
//...
}
Class TypeB
{
List<TypeC> MyListOfTypeC;
//...
}
Class TypeC
{
int SomeInteger;
//...
}
Given List<TypeA> MyListOfTypeA
, I want to search for all TypeC objects that satisfy a certain condition, like SomeInteger> 100. Besides embedding in / foreach loops, what is the Linq way of doing this?
var MyListOfTypeA = new List<TypeA>();
// ...
var cItems =
from a in MyListOfTypeA
from b in a.MyListOfTypeB
from c in a.MyListOfTypeC
where c.SomeInteger > 100
select c;
The above is equivalent to a SelectMany
LINQ function call , but in my opinion it is significantly cleaner and easier to read.
Doing this with LINQ functions (as already suggested by Dmitry, albeit with some modifications):
var cItems =
MyListOfTypeA.SelectMany( a => a.MyListOfTypeB )
.SelectMany( b => b.MyListOfTypeC )
.Where( c => c.SomeValue > 200 );
Something like this is what you are looking for, I think:
var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB.SelectMany(c => c.MyListOfTypeC.Select(x => x.SomeInteger > 100))).ToList();
You can do it like this using Linq:
var myListOfTypeA = new List<TypeA>();
// fill your list here
var typeCs = from typeA in myListOfTypeA
from typeB in typeA.MyListOfTypeB
from typeC in typeB.MyListOfTypeC
where typeC.SomeInteger > 100
select typeC;
You need to navigate through all sublists and what from
can do for you.
var ta = new TypeA();
var allTypeCsThatSatisfyMyCondition =
from tb in ta.MyListOfTypeB // This will iterate to each item in the list
from tc in tb.MyListOfTypeC // This will iterate to each item in the *sublist*
where tc.SomeInteger > 100 // Condition could be anything; filter the results
select tc; // When you select, you tell your iterator to yield return that value to the caller.
return allTypeCsThatSatisfyMyCondition.ToList(); // To list will force the LINQ to execute and iterate over all items in the lists, and add then to a list, effectively converting the returned items to a list.