我有以下订单对象,其中包含订单插件列表。我正在尝试创建一个报告,显示所有插件类型及其数量总和。
public class Order {
public IList<OrderAddon> OrderAddons { get; set; }
}
public class OrderAddon {
public enum OrderType { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
这就是我所处的位置,无法弄清楚整个查询是否错误,我只是错过了什么。
var query = from order in Model.Orders
from addon in order.OrderAddons
group order by addon.AddonType
into orderAddons select new
{
Name = orderAddons.Key,
Quantity = orderAddons.Sum(x => x.) << This is where I am stuck
};
当我击中时。我的intellisense在订单对象中显示属性而不是插件对象。
答案 0 :(得分:4)
那是因为你说的是group order by ...
,所以orderAddons
对象变成了order
的分组。如果你需要两个对象的属性,你可以使用它:
from order in Model.Orders
from addon in order.OrderAddons
group new{addon, order} by addon.AddonType
into orderAddons select new
{
Name = orderAddons.Key,
Quantity = orderAddons.Sum(x => x.addon.Quantity)
};
如果这是您需要的所有数据,这有点简单:
from order in Model.Orders
from addon in order.OrderAddons
group order.Quantity by addon.AddonType
into quantityByAddonType select new
{
Name = quantityByAddonType.Key,
Quantity = quantityByAddonType.Sum()
};
答案 1 :(得分:4)
替代语法相同的结果...
var result = Model.Orders
.SelectMany(order => order.OrderAddons)
.GroupBy(addon => addon.OrderType)
.Select(grouping => new
{
Name = grouping.Key,
Quantity = grouping.Sum(addon => addon.Quantity)
});