GROUPBY和Select扩展方法帮助 [英] GroupBy and Select extension method assistance

查看:266
本文介绍了GROUPBY和Select扩展方法帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用下面的代码GROUPBY几个领域:

I am trying to GroupBy a few fields using the following code:

var cars = tmp.Select(a => new { a.Make, a.Model, a.Year });

cars = cars.Distinct()
           .OrderBy(a => a.Make)
           .ThenBy(a => a.Model);

var groupedCars = cars.GroupBy(a => new { a.Make, a.Model })
                      .Select(b => new { b.Make, b.Model, b.Year });



不幸的是,代码的最后一行是给我的错误,是不承认的三个字段。

Unfortunately, the very last line of code is giving me errors as is does not recognize the three fields.

System.Linq.IGrouping(AnonymousType#1,#AnonymousType 2)'不包含'制作'的定义,并没有扩展法'制作'接受一个类型的第一个参数'System.Linq.IGrouping(AnonymousType#1,#AnonymousType 2)'可以找到(是否缺少using指令或程序集引用?)

'System.Linq.IGrouping(AnonymousType#1,AnonymousType#2)' does not contain a definition for 'Make' and no extension method 'Make' accepting a first argument of type 'System.Linq.IGrouping(AnonymousType#1,AnonymousType#2)' could be found (are you missing a using directive or an assembly reference?)

这是所有三个字段(品牌,型号,年份)同样的错误。

It is the same error for all three fields (Make, Model, Year).

任何想法如何解决这一问题?

Any ideas how to fix this?

推荐答案

一旦你通过分组品牌和型号的汽车,该序列的每个元素都是一个组。你可以得到与属性组键,这样你就可以找到该组的制作模型,但年度是没有意义的......会有每组多辆,而且他们都可以有不同的年。您可以使用这些信息的的小组,当然。例如:

Once you've grouped the cars by make and model, each element of the sequence is a group. You can get the key for the group with the Key property, so you can find the group's Make and Model, but Year makes no sense... there will be multiple cars in each group, and they could all have different years. You can use the information within the group, of course. For example:

var groupedCars = cars.GroupBy(a => new { a.Make, a.Model })
                      .Select(g => new { g.Key.Make, g.Key.Model,
                                         MinYear = g.Min(car => car.Year),
                                         MaxYear = g.Max(car => car.Year) });



不过,从根本上,你必须考虑一个事实,即序列的每个元素是一个组,不一个单一的汽车。

But fundamentally you need to be thinking about the fact that each element of the sequence is a group, not a single car.

这篇关于GROUPBY和Select扩展方法帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆