带有大量嵌套列表的列表上的LINQ

时间:2013-09-11 08:44:14

标签: c# linq

我遇到嵌套列表的问题。所以我有3个课程:

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;}
}

我想从Class1中选择Class2.Name =“something”的所有Class3.Name,重要的是结果将是 IEnumerable string 。我该如何解决?

2 个答案:

答案 0 :(得分:6)

LINQ表达式可以有多个嵌套的from子句:

// 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;

为了完整性,这里有两种使用方法语法的变体:

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)));

答案 1 :(得分:0)

 List<string> listNames = Class1.Where(f => f.Class2List.Where(g => string.Compare(g.Name, "something") == 0)).Select(h => h.Name).ToList()