如何从最高长度的嵌套列表中获取列表
本文关键字:列表 嵌套 获取 高长度 | 更新日期: 2023-09-27 18:16:00
下面是我的类结构:
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; }
}
现在我试图得到的ChildLevelList1,其长度是最高的所有其他ChildLevelList1为每个TopLevel记录。如果找到,则返回顶层记录的ChildListLevel1列表
例如:假设我有如下记录:
TopLevel[0]: ChildLevelList1 (Length =3)
TopLevel[1]: ChildLevelList1 (Length =4)
TopLevel[2]: ChildLevelList1 (Length =8) //get this list
TopLevel[3]: ChildLevelList1 (Length =2)
所以我想得到ChildLevelList为TopLevel 2,即从第三个位置,如下所示:
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.
}
首先我选择了一些更好的名字来避免混淆
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; }
}
并获取长度最大的List
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();