LINQ 多列分组详解
在 SQL 中,可以使用 GROUP BY
子句根据多个列对数据进行分组。例如:
SELECT * FROM <tablename> GROUP BY <column1>,<column2>
如何在 LINQ 中实现类似的功能呢?
使用匿名类型
一种方法是使用匿名类型。以下是一个示例:
var groupedData = x.GroupBy(x => new { x.Column1, x.Column2 });
这段代码根据 x
序列中元素的 Column1
和 Column2
属性对元素进行分组,为每个唯一的值组合创建一个匿名类型。
数据示例
考虑以下数据结构:
public class QuantityBreakdown { public int MaterialID { get; set; } public int ProductID { get; set; } public float Quantity { get; set; } }
以及以下 INSERT 语句:
INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM(Quantity) FROM @Transactions GROUP BY MaterialID, ProductID
可以使用以下代码将此转换为 LINQ:
var groupedTransactions = transactions .GroupBy(t => new { t.MaterialID, t.ProductID }) .Select(g => new QuantityBreakdown { MaterialID = g.Key.MaterialID, ProductID = g.Key.ProductID, Quantity = g.Sum(t => t.Quantity) });
此 LINQ 表达式按 MaterialID
和 ProductID
对事务进行分组,然后计算每个组的 Quantity
值之和。
以上是如何通过LINQ中的多列分组数据?的详细内容。更多信息请关注PHP中文网其他相关文章!