简体   繁体   English

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

[英]How to get list from nested list with highest length?

Below is my class structure: 下面是我的课程结构:

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

Now i am trying to get that ChildLevelList1 whose length is highest among all other ChildLevelList1 for each TopLevel records.If found then return that list of ChildListLevel1 for that Top level record 现在我正在尝试获取每个TopLevel记录中所有其他ChildLevelList1中长度最大的ChildLevelList1.If找到了,则返回该顶层记录的ChildListLevel1列表

For eg: suppose i have records like below: 例如:假设我有如下记录:

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

So I would like to get ChildLevelList for TopLevel 2 ie from third position like below: 所以我想从第二个位置获得TopLevel 2的ChildLevelList:

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

I am trying to get in below variable: 我试图进入下面的变量:

var childLevelList1 // trying to get in this varaible

This is how I am trying: 这就是我正在尝试的方法:

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

First of all I choose some better names to avoid confusion 首先,我选择一些更好的名字以避免混淆

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

And to get the List with the highest length 并获得长度最大的列表

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM