如何在LINQ中将更多列添加到分组结果中?

时间:2018-07-20 08:25:03

标签: c# linq grouping

我有这个LINQ语句,它产生一个字符串集合:

enter image description here

如何更改此LINQ查询,以使其生成int / string数组的集合,以便可以在结果中包括语言ID?

类似这样的东西:

from u in Users
join l in Languages on u.LanguageId equals l.Id
group u by l.Name into g
orderby g.Count() descending
select new { Id = l.Id, NameAndCount = g.Key + " (" + g.Count() + ")" }

尝试失败:

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:4)

您可以简单地按Id对记录进行分组,然后使用Name来获取FirstOrDefault

from u in Users
join l in Languages on u.LanguageId equals l.Id
group l by l.Id into g
orderby g.Count() descending
select new { Id = g.Key, NameAndCount = g.First().Name + " (" + g.Count() + ")" }

答案 1 :(得分:2)

您只需要对代码进行一些更改。 与其按用户分组,不如按语言和该组的两个字段/列分组。

from u in Users
join l in Languages on u.LanguageId equals l.Id
group l by new { l.Id, l.Name } into g
orderby g.Count() descending
select new { Id = g.Key.Id, NameAndCount = g.Key.Name + " (" + g.Count() + ")" }

另一种情况:

请注意,可以从.Key访问我们用于分组的每个字段,您可以命名字段

示例1。

// ...
group l by new { MyId = l.Id, MyName = l.Name } into g
orderby g.Count() descending
select new { Id = g.Key.MyId, NameAndCount = g.Key.MyName + " (" + g.Count() + ")" }

如果在另一种情况下,我们不想丢失结果中的集合,只需添加一个UserList变量,如下例所示。

示例2:

// ...
group l by new { l.Id, l.Name } into g
orderby g.Count() descending
select new { Id = g.Key.Id, NameAndCount = g.Key.Name + " (" + g.Count() + ")", UserList = g.ToList() }