Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ on List with lot of nested List

Tags:

c#

linq

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?

like image 608
Vajda Endre Avatar asked Sep 11 '13 08:09

Vajda Endre


2 Answers

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)));
like image 142
Heinzi Avatar answered Nov 17 '22 20:11

Heinzi


 List<string> listNames = Class1.Where(f => f.Class2List.Where(g => string.Compare(g.Name, "something") == 0)).Select(h => h.Name).ToList()
like image 1
mggSoft Avatar answered Nov 17 '22 20:11

mggSoft