我在每个订单中有一个订单数组是一个项目数组。如何按项目名称对所有订单进行分组,并获取订购商品的总和。在这种情况下,输出将是:
输出
Item01 : quantity = 2;
Item02 : quantity = 45;
GetOrders
public Order[] GetOrders()
{
Order[] orders = new Order[]
{
new Order
{
id = 1,
orderLines = new OrderLine[]
{
new OrderLine
{
itemName = "Item 01",
quantity = 1
},
new OrderLine
{
itemName = "Item 02",
quantity = 3
},
},
},
new Order
{
id = 2,
orderLines = new OrderLine[]
{
new OrderLine
{
itemName = "Item 01",
quantity = 1
},
new OrderLine
{
itemName = "Item 02",
quantity = 42
}
}
}
};
...
我尝试了以下内容:
foreach (var order in orders)
{
foreach (var orderline in order.orderLines.GroupBy(x => x.itemName).Select(group => new
{
Metric = group.Key,
Count = group.Count()
}))
{
Console.WriteLine("{0} {1}", orderline.Metric, orderline.Count);
}
}
但它只为每个项目返回1。我对编程比较陌生,所以对我来说很容易。谢谢
答案 0 :(得分:2)
要获取所有订购商品的总和,请使用以下查询:
var results =
(from order in orders
from orderLine in order.orderLines
group orderLine by orderLine.itemName into orderLineGrouping
let totalQuantity = orderLineGrouping.Sum(ol => ol.quantity)
select new { itemName = orderLineGrouping.Key, metric = totalQuantity }).ToList();
results.ForEach(resultItem => Console.WriteLine("{0} {1}", resultItem.itemName, resultItem.metric);
答案 1 :(得分:1)
展平OrderLines
你需要让自己熟悉Enumerable.SelectMany
这是
来自LINQ的SelectMany 将许多元素折叠为一个元素 采集。生成的集合是另一种元素类型。我们 指定元素如何转换为其他元素的集合 元件。
var summary = orders.Where(x => x.OrderLines != null) // Check for null as there seems to be null orderlines in your model
.SelectMany(x => x.OrderLines) // Flatten
.GroupBy(x => x.itemName) // Group
.Select(group => new // Project
{
ItemName = group.Key,
TotalQuantity = group.Sum(x => x.quantity)
})
.ToList(); // To List
提示 :为itemName
和quantity
下表总结了资本化规则 标识符并提供不同类型的示例 标识符
抱歉我的OCD刚刚开始
答案 2 :(得分:1)
参见代码:
var output = orders.SelectMany(x => x.orderLines)
.GroupBy(x => x.itemName, x => x.quantity)
.Select(x => $"{x.Key} : quantity = {x.Sum(y => y)}");