如何使用 linq 对集合进行分组和排序?

Nov*_*Net 1 c# linq

我正在这样做,但它不起作用(不编译),我需要先 GroupBy 然后 OrderBy。

lstOrderItems.OrderBy(x => x.itemPrice).GroupBy(p => p.CatID);
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 5

你这里理解有问题。如果你进行分组,你将有一个可以使用的属性:密钥。

我以 Northwind 数据库和产品表作为参考。如果您按 CategoryId 对产品进行分组,那么Products.GroupBy (p => p.CategoryID)您当然可以附加 OrderBy。但之后您可以订购的唯一属性是 key:

//p.Key is the CategoryId after which you grouped by
Products.GroupBy (p => p.CategoryID).OrderBy (p => p.Key)
Run Code Online (Sandbox Code Playgroud)

您需要做的是选择分组并使用它:

Products.GroupBy (p => p.CategoryID).Select (p => p.OrderBy (x => x.UnitPrice))
Run Code Online (Sandbox Code Playgroud)

如果你想展平你的结果使用SelectMany

Products.GroupBy (p => p.CategoryID).SelectMany (p => p.OrderBy (x => x.UnitPrice))
Run Code Online (Sandbox Code Playgroud)

编辑 澄清 Select/SelectMany 问题:这就是您将使用的Select。返回类型为IOrderedQueryable<IOrderedEnumberable<Products>>. 本质上是列表中的列表。

在此输入图像描述

如果使用SelectMany(),则可以将列表中的此列表扁平化为一个列表

在此输入图像描述