简体   繁体   English

使用 linq 按父项对对象列表进行分组以输出子元素

[英]Grouping a list of objects by parent using linq to output child elements

I have a silly problem with a linq groupby I just cant get to work on my own.我对 linq groupby 有一个愚蠢的问题,我无法独自工作。

Basically I have a list of items that I am trying to group together by its parentId outing the details基本上我有一个项目列表,我试图通过它的 parentId 将详细信息分组在一起

var list = new List<GroupItem>()
{
    new GroupItem() {Id = 1, Name = ".net"},
    new GroupItem() {Id = 2, Name = "asp.net", ParentId = 1},
    new GroupItem(){Id = 3,Name = "c#",ParentId = 1},
    new GroupItem(){Id = 4,Name = "php"},
    new GroupItem(){Id = 5,Name = "zend",ParentId = 4}
};

var group = from g in list
            group g by g.ParentId ==null
                into grouped
            select new
            {
                FrameworkId = grouped.Key,
                Items = (from g in list
                        where g.ParentId==g.ParentId
                        select g).ToList()

            };

foreach (var gi in group)
{

    Console.WriteLine(gi.FrameworkId);
    foreach (var item in gi.Items)
    {
        Console.WriteLine(item.Name);
    }
}

What am I doing wrong?我究竟做错了什么?

You query seems to be too complicated:你的查询好像太复杂了:

  1. You should group by ParentId for items that have it not null对于不为空的项目,您应该按ParentId分组
  2. You do not need to find the items again by matching ParentId because GroupBy operator does it for you您不需要通过匹配ParentId再次查找项目,因为GroupBy运算符会为您完成

My preferred solution:我的首选解决方案:

list.Where(x => x.ParentId != null)
    .GroupBy(x => x.ParentId, 
             (key, elements) => 
                new {
                  FrameworkId = key,
                  Items = elements.ToList()
                })
    .ToList();

You can Directlly use this query for filtering Data.您可以直接使用此查询来过滤数据。

if you want the data which don't have ParentID then you can use below mentioned query如果您想要没有 ParentID 的数据,那么您可以使用下面提到的查询

 var gr = list.Where(p => p.ParentId == 0).ToList();

and if you want the data who have the Parent Id then you can use below mentioned code如果您想要具有父 ID 的数据,则可以使用下面提到的代码

 var gr1 = list.Where(p => p.ParentId != 0).ToList();

here is my solution:这是我的解决方案:

 list.Where(x => x.ParentId != null)
  .GroupBy(x => x.ParentId)
  .Select(x => new ParentViewModel {
     ParentId = x.Key.ParentId,
     Parent = x.ToList()
  })
  .ToList();

Now you will get child items in Parent object of ParentViewModel , eg Parent.Items现在您将在ParentViewModel Parent 对象中获得子项,例如Parent.Items

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

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