c# - GroupBy 和 Select 扩展方法帮助

标签 c# linq extension-methods

我尝试使用以下代码对几个字段进行分组:

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 });

不幸的是,最后一行代码给了我错误,因为它无法识别这三个字段。

'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?)

所有三个字段(品牌、型号、年份)均出现相同的错误。

有什么想法可以解决这个问题吗?

最佳答案

按品牌和型号对汽车进行分组后,序列中的每个元素都是一个组。您可以使用 Key 属性获取组的 key ,这样您就可以找到该组的 MakeModel,但是 Year 没有任何意义...每个组中都会有多辆车,并且它们的年份都可能不同。当然,您可以使用组内的信息。例如:

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) });

但从根本上来说,您需要考虑这样一个事实:序列中的每个元素都是一个组,而不是一辆汽车。

关于c# - GroupBy 和 Select 扩展方法帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22695334/

相关文章:

c# - 使用 SaveFileDialog 后 GDI+ 的 Bitmap.Save() 发生一般错误

c# - LINQ 可以用于在字符串中搜索 Regex 表达式吗?

c# - linq 确定 list<string> 中的字段名称是否在 list<Class> 的字段选择中找到

c# - 在 LINQ to SQL 中链接多个表

swift - 如何扩展 Decodable 以从字典初始化?

f# - 在 F# 中扩展枚举类型

c# - dirs.proj 是如何使用的?

c# - NHibernate 3.1 查询等于

c# - Linq 中的WhereSelectArrayIterator 是什么?

c# - 如果长度恰好为一个,或者否则为默认值,我如何获得 IEnumerable 的第一个值?