如何从列表中创建树列表

时间:2017-07-24 11:01:39

标签: linq c#-4.0

我被困在将普通列表转换为树类型列表。我必须转换如下格式: 我们可以创建一个父子关系列表吗?

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 个答案:

答案 0 :(得分: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属性。如果需要,你也可以得到它,但是拥有整个对象最有可能帮助的不仅仅是一个属性。