[英]How do I group a list using Linq
The scenario I have is as follows: 我的情况如下:
I have the following data - 我有以下数据-
1, samename, Grand Central, New York, 12
2, samename, Opera House, Sydney, 12
3, samename, Opera House, Sydney, 12
4, name2, Emirates, London, 13
5, name3, Opera House, Sydney, 14
And I would like to output it as two tables 我想将其输出为两个表
12, samename
13, name2
14, name3
Grand Central, New York, 12
Opera House, Sydney, 12
Opera House, Sydney, 12
Emirates, London, 13
Opera House, Sydney, 14
This was really bad design that I have inherited - and I am trying to make it better.. without breaking the old code. 我继承的这确实是一个糟糕的设计-我正在尝试使其更好..而不破坏旧代码。
You need to do it in two steps, first group them on Name
and GroupID
: 您需要分两步进行操作,首先将它们
GroupID
在Name
和GroupID
:
var result = list.GroupBy(x=>new {x.GroupID, x.Name})
.Select(g=> new { GroupID = g.Key.GroupID, Name = g.Key.Name});
and in second case group them with other three columns ( GroupID
, Place
and Location
): 在第二种情况下,
Place
它们与其他三列( GroupID
, Place
和Location
) GroupID
:
var result = list.GroupBy(x=>new {x.GroupID, x.Location,x.Place})
.Select(g=> new
{
GroupID = g.Key.GroupID,
Location = g.Key.Location,
Place = x.Key.Place
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.