如何从最长的嵌套列表中获取列表?

时间:2016-11-02 12:25:18

标签: c# .net linq

以下是我的班级结构:

 public class TopLevel
    {
        public int Id { get; set; }
        public List<ChildLevelList> ChildLevelList { get; set; }
    }

public class ChildLevelList
    {
        public int Id { get; set; }
        public List<ChildLevelList1> ChildLevelList1 { get; set; }
    }

public class ChildLevelList1
    {
        public int Id { get; set; }
    }

现在我试图获取每个TopLevel记录的所有其他ChildLevelList1中长度最高的ChildLevelList1。如果找到则返回该顶级记录的ChildListLevel1列表

例如:假设我有以下记录:

TopLevel[0]: ChildLevelList1 (Length =3)
TopLevel[1]: ChildLevelList1 (Length =4)
TopLevel[2]: ChildLevelList1 (Length =8) //get this list
TopLevel[3]: ChildLevelList1 (Length =2)

所以我想获得TopLevel 2的ChildLevelList,即第三个位置,如下所示:

Output:[2]: ChildLevelList1 (Length =8)

我试图进入下面的变量:

var childLevelList1 // trying to get in this varaible

这就是我的尝试:

for (int i = 0; i < List.Count(); i++)
        {
           //Sorry  but not getting how to do this.    
        }

2 个答案:

答案 0 :(得分:2)

首先,我选择一些更好的名字以避免混淆

public class TopLevel
{
    public int Id { get; set; }
    public List<ChildLevel> ChildLevelList { get; set; }
}

public class ChildLevel // was ChildLevelList
{
    public int Id { get; set; }
    public List<ChildLevel1> ChildLevelList1 { get; set; }
}

public class ChildLevel1 // was ChildLevel1List
{
    public int Id { get; set; }
}

获取最长的列表

public List<ChildLevel1> GetBiggestChildLevel1List( IEnumerable<TopLevel> source )
{
    return source
        .SelectMany( t => t.ChildLevelList )   // IEnumerable<ChildLevel>
        .Select( c1 => c1.ChildLevelList1 )    // IEnumerable<List<ChildLevel1>>
        .OrderByDescending( c2l => c2l.Count ) // IEnumerable<List<ChildLevel1>>
        .FirstOrDefault();
}

答案 1 :(得分:1)

您将从TopLevel向下两个级别,因此您可以尝试使用以下LINQ查询:

var result = List.OrderByDescending(x => x.ChildLevelList.Select(y => y.ChildLevelList1.Count())).First();