在 C# 中获取分组或透视数据表中的值通常涉及使用 LINQ(Language Integrated Query)来对数据进行分组和聚合。以下是一个示例,演示如何使用 LINQ 来实现这一点。
假设我们有一个包含销售数据的列表,我们希望按产品分组并计算每个产品的总销售额。
首先,我们定义一个简单的销售数据类和一个包含示例数据的列表:
using System;
using System.Collections.Generic;
using System.Linq;
public class Sale
{
public string Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
public class Program
{
public static void Main()
{
List<Sale> sales = new List<Sale>
{
new Sale { Product = "Apple", Quantity = 10, Price = 1.2m },
new Sale { Product = "Banana", Quantity = 5, Price = 0.8m },
new Sale { Product = "Apple", Quantity = 7, Price = 1.2m },
new Sale { Product = "Banana", Quantity = 3, Price = 0.8m },
new Sale { Product = "Orange", Quantity = 8, Price = 1.5m }
};
// 使用 LINQ 进行分组和聚合
var groupedSales = from sale in sales
group sale by sale.Product into productGroup
select new
{
Product = productGroup.Key,
TotalQuantity = productGroup.Sum(s => s.Quantity),
TotalSales = productGroup.Sum(s => s.Quantity * s.Price)
};
// 打印结果
foreach (var group in groupedSales)
{
Console.WriteLine($"Product: {group.Product}, Total Quantity: {group.TotalQuantity}, Total Sales: {group.TotalSales:C}");
}
}
}
Product
、Quantity
和 Price
属性。Sale
对象的列表。from ... in ... group ... by ... into ...
语法按产品分组。select new
创建一个匿名对象,包含产品名称、总数量和总销售额。运行上述代码后,你将看到类似以下的输出:
Product: Apple, Total Quantity: 17, Total Sales: $20.40
Product: Banana, Total Quantity: 8, Total Sales: $6.40
Product: Orange, Total Quantity: 8, Total Sales: $12.00
除了查询语法,你还可以使用 LINQ 的方法语法来实现相同的功能:
var groupedSales = sales
.GroupBy(sale => sale.Product)
.Select(productGroup => new
{
Product = productGroup.Key,
TotalQuantity = productGroup.Sum(s => s.Quantity),
TotalSales = productGroup.Sum(s => s.Quantity * s.Price)
});
foreach (var group in groupedSales)
{
Console.WriteLine($"Product: {group.Product}, Total Quantity: {group.TotalQuantity}, Total Sales: {group.TotalSales:C}");
}
领取专属 10元无门槛券
手把手带您无忧上云