I have got trouble with nested lists. So I have 3 class:
public class Class1
{
public string Name {get;set;}
public List<Class2> Class2List {get;set;}
}
public class Class2
{
public string Name {get;set;}
public List<Class3> Class3List {get;set;}
}
public class Class3
{
public string Name {get;set;}
}
I would like to select all Class3.Name where Class2.Name = "something" from Class1 and important that the result will be IEnumerable string . How should I resolve it?
LINQ expressions can have multiple nested from
clauses:
// nested from clauses
var names = from c1 in myClass1List
from c2 in c1.Class2List
where c2.Name == "something"
from c3 in c2.Class3List
select c3.Name;
For completeness, here are two variants using method syntax:
var names = myClass1List
.SelectMany(c1 => c1.Class2List.Where(c2 => c2.Name == "something"))
.SelectMany(c2 => c2.Class3List.Select(c3 => c3.Name));
var names = myClass1List
.SelectMany(c1 => c1.Class2List
.Where(c2 => c2.Name == "something")
.SelectMany(c2 => c2.Class3List
.Select(c3 => c3.Name)));
List<string> listNames = Class1.Where(f => f.Class2List.Where(g => string.Compare(g.Name, "something") == 0)).Select(h => h.Name).ToList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With