2016-11-02 91 views
0

下面是我的階級結構:如何從最長的嵌套列表中獲取列表?

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每個頂層records.If中最高尋到然後返回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的頂層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.  
     } 
+2

'VAR childLevelList1 = TopLevels.Select(TL => tl.ChildLevelList))OrderByDescending(名單=> list.Count)。首先()' –

+0

@Learning - 說實話...你已經嘗試是不是真的try..Next時請提供具有更多嘗試它.. –

+0

@GiladGreen好吧,我同意你的看法,但我一直在堅持的邏輯點點,我也不好使用LINQ所以我問這兒過得想就像把指數爲2,即1個F或子指標的父指標和1,然後循環和比較但這是太複雜 –

回答

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

越來越ChildLevelList1謝謝你多的答案,您對在幫助我,請幫助保持這樣的:) –

1

您正在下降兩個級別從TopLevel,因此,你可以用下面的LINQ查詢嘗試:

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

您返回頂層項目,而不是它是在這裏問 –

+0

非常感謝你的回答和你對幫助我那種努力列表那種努力並請繼續幫助像這樣:) –