简体   繁体   English

C# LINQ GroupBy 将列表转换为具有一个属性作为值列表的组

[英]C# LINQ GroupBy to convert a List to a group with one property as List of values

I have a list of objects list1我有一个对象列表list1

Name Value
N1   V100 
N2   V101
N1   V102
N4   V103
N4   V104

I want to convert this into a grouped List我想将其转换为分组列表

Name Values
N1   V100, V102 
N2   V101
N4   V103, V104

When I use GroupBy I get the whole thing, ( list1.GroupBy(key => key.Name) )当我使用GroupBy时,我得到了全部, ( list1.GroupBy(key => key.Name) )

Name Values
N1
  N1   V100
  N1   V102
N2
  N2   V101
N4
  N4   V103
  N4   V104

I just want the values as a List.我只想将值作为列表。

After GroupBy , use ToDictionary :GroupBy之后,使用ToDictionary

source.GroupBy(x => x.Name)
      .ToDictionary(x => x.Key, x => x.Select(e => e.Value).ToList());

This yields a Dictionary<string, List<string>> where the keys are the names and the values are lists made up of projecting each element to a string under that specific group.这会产生一个Dictionary<string, List<string>> ,其中键是名称,值是由将每个元素投影到该特定组下的string组成的列表。

I assume that Value is a string for example purposes only but in reality, it doesn't really matter as the solution remains the same.我假设Value是一个string ,仅用于示例目的,但实际上,它并不重要,因为解决方案保持不变。

Adding another answer here by someone, (which seems to have been deleted, I was trying that approach and got it to work too).某人在这里添加另一个答案,(似乎已被删除,我正在尝试这种方法并使其也起作用)。
All credit goes to that anonymous person.所有的功劳都归于那个匿名的人。

    source.GroupBy(x => x.Name, y=> y.Value)
          .Select( result => new { Name = result.Name,
                                   Values = result.Select(r=> r.Value).ToList() } );

The dictionary solution seems to be more intuitive as I can see all the transformations happening to generate the result.字典解决方案似乎更直观,因为我可以看到生成结果时发生的所有转换。

EDIT:编辑:

Spent way too much time on this, here are 2 other ways to make this happen:-在这上面花了太多时间,这里有两种其他方法可以实现这一目标:-

source.GroupBy(grpKey => grpKey.Name, 
                   elementSelector => elementSelector,
                   (resultSelectorName, resultSelectorValues ) => new 
                   {
                     Name = resultSelectorName,
                     Values = resultSelectorValues.Select(v=>v.Value).ToList() 
                   });

2) 2)

source.GroupBy(grpKey => grpKey.Name, 
               elementSelector => elementSelector.Value,
               (resultSelectorName, resultSelectorValue ) => new 
               {
                 Name = resultSelectorName,
                 Values = resultSelectorValue.ToList() 
               });

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

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