简体   繁体   English

C#中同级的Group和Non Group列表项

[英]Group and Non Group list items at same level in C#

I have list that has few items and I want the final result as a combination of groups and items at a same level.我的列表中的项目很少,我希望最终结果是同一级别的组和项目的组合。

Example:例子:

public class Response
{
    public int? Id { get; set; }
    public int? Parent { get; set; }        
    public string ItemDescription { get; set; }
    public string CommonDescription { get; set; }
    public IEnumerable<Response> Children { get; set; }
}

var tempResult = GetFromdatabase(); //getting records from database and the type is List<Response>
//The above variable contains all the data as flat structure, means all the items where Parent is null and items with Parent

Now I want the final result to be looks like this:现在我希望最终结果看起来像这样:

[
    {
       "id": 1,
       "itemDescription": "Desc 1",
       "commonDescription": "Com. desc 1"
    },
    {
       "id": 2,
       "itemDescription": "Desc 2",
       "commonDescription": "Com. desc 2"
    },
    {
       "Parent": 3,
       "Children":[
         {
            "id": 4,
            "itemDescription": "Desc 4",
            "commonDescription": "Com. desc 4"
         },
         {
            "id": 5,
            "itemDescription": "Desc 5",
            "commonDescription": "Com. desc 5"
         }
       ]
    }
]

I am trying to group by with "Parent", but failing where it's null .我试图用“父母” group by ,但在null的地方失败了。 I also tried to append in the select, but the syntax seems not supported.我也试过select中的append,但是语法好像不支持。

use Lookup like this:像这样使用查找

    IEnumerable<Response> GetHierarhicalResponse(IEnumerable<Response> items) {
        var lookup = items.Where(i => i.Parent != null).ToLookup(i => i.Parent);
        foreach(var item in items)
            item.Children = lookup[item.Id];
        return items.Where(i => i.Parent == null);
    }

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

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