2017-07-24 32 views
2

我被困在將普通列表轉換爲樹型列表。我必須像下面的格式轉換: 我們可以創建父子關係列表嗎?如何從列表中創建樹列表

State 
County 
    Name 
    Name2 
County 
    Name3 
    Name4 

而下面是我的名單:

{ 
    "data": [ 
     { 
      "name": "D1", 
      "stateName": "Georgia", 
      "stateId": 1, 
      "countyName": "Apache", 
      "countyId": 1 
     }, 
     { 
      "name": "D2", 
      "stateName": "Georgia", 
      "stateId": 1, 
      "countyName": "Apache", 
      "countyId": 1 
     }, 
     { 
      "name": "D3", 
      "stateName": "Georgia", 
      "stateId": 1, 
      "countyName": "Apache", 
      "countyId": 1 
     }, 
     { 
      "name": "D4", 
      "stateName": "Georgia", 
      "stateId": 1, 
      "countyName": "Apache", 
      "countyId": 1 
     }, 
     { 
      "name": "D5", 
      "stateName": "Georgia", 
      "stateId": 1, 
      "countyName": "Catron", 
      "countyId": 2 
     } 
    ], 
    "totalRowCount": 0, 
    "errors": [] 
} 

有沒有辦法,我能有樹列表中的任何方式。任何幫助將不勝感激。

我使用下面的代碼樹列表,但它沒有給我正確的數據。

var lstTaxLocation = (from loc in _queryEntities.TaxLocations 
            join st in _queryEntities.States on loc.StateId equals st.Id 
            join cou in _queryEntities.Counties on loc.CountyId equals cou.Id 
            group new { loc, st, cou } by new { st.Id } into pg 
            let datagroup = pg.FirstOrDefault() 
            let location = datagroup.loc 
            let state = datagroup.st 
            let county = datagroup.cou 
            select new TaxLocationDto 
            { 
             Name = location.Name, 
             StateId = state.Id, 
             StateName = state.Name, 
             CountyName = county.Name, 
             CountyId = county.Id 
            }); 

回答

1

這對於LINQ來說非常簡單。

假設你有你的數據已經反序列化到C#對象:

public class Data 
{ 
    public string Name { get; set; } 
    public string StateName { get; set; } 
    public int StateId { get; set; } 
    public string CountyName { get; set; } 
    public int CountyId { get; set; } 
} 

然後可以使用LINQ的GroupBySelectMany

var treeList = data.GroupBy(d => d.StateName) 
        .SelectMany(group => group.GroupBy(d => d.CountyName)); 

這會給你你正在尋找的結構,但每個「節點」將是整個對象,而不僅僅是Name財產。如果需要的話,你也可以得到它,但是讓整個對象最有可能幫助更多的不僅僅是一個屬性。

+0

我不能使用ThenBy方法。 – Python

+0

謝謝,這是我的第一次開始我的一天。 'ThenBy'只是'OrderBy'的必然結果。我已經更新了我的答案,以便爲您提供所需的信息。 – krillgar

+0

它正在檢索數據,但它不是輸入到Ilist的類型。它給了我一個錯誤:「無法投射類型爲'Grouping [my class]'的對象來鍵入我的課程'' – Python