简体   繁体   中英

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 . I also tried to append in the select, but the syntax seems not supported.

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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