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

我有一个对象列表list1


Name Value

N1   V100 

N2   V101

N1   V102

N4   V103

N4   V104

我想将其转换为分组列表


Name Values

N1   V100, V102 

N2   V101

N4   V103, V104

当我使用时,GroupBy我得到了整个东西,( list1.GroupBy(key => key.Name) )


Name Values

N1

  N1   V100

  N1   V102

N2

  N2   V101

N4

  N4   V103

  N4   V104

我只想将值作为列表。


斯蒂芬大帝
浏览 194回答 2
2回答

白板的微信

之后GroupBy,使用ToDictionary:source.GroupBy(x&nbsp;=>&nbsp;x.Name) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ToDictionary(x&nbsp;=>&nbsp;x.Key,&nbsp;x&nbsp;=>&nbsp;x.Select(e&nbsp;=>&nbsp;e.Value).ToList());这会产生一个Dictionary<string, List<string>>,其中键是名称,值是由将每个元素投影到string该特定组下的列表组成的列表。我认为这Value只是一个string示例目的,但实际上,这并不重要,因为解决方案保持不变。

心有法竹

有人在此处添加另一个答案(似乎已被删除,我正在尝试这种方法并使其也可以正常工作)。所有的功劳都归于那个匿名的人。&nbsp; &nbsp; source.GroupBy(x => x.Name, y=> y.Value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select( result => new { Name = result.Name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Values = result.Select(r=> r.Value).ToList() } );字典解决方案似乎更直观,因为我可以看到为生成结果而发生的所有转换。编辑:在这上面花了太多时间,这里有另外两种方法可以实现这一点:-source.GroupBy(grpKey => grpKey.Name,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;elementSelector => elementSelector,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(resultSelectorName, resultSelectorValues ) => new&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Name = resultSelectorName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Values = resultSelectorValues.Select(v=>v.Value).ToList()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});2)source.GroupBy(grpKey => grpKey.Name,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;elementSelector => elementSelector.Value,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(resultSelectorName, resultSelectorValue ) => new&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Name = resultSelectorName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Values = resultSelectorValue.ToList()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP