我想根据数量加入2个实体的结果。这就是我所拥有的......
订单#1
OrderID CustomerID ItemID Description POS# Cost Quantity
1 1 1 Apples 111 1.25 3
1 1 2 Oranges 222 1.12 5
1 1 3 Bananas 333 1.17 5
订单#2
OrderID CustomerID ItemID Description POS# Cost Quantity
2 1 1 Apples 111 1.25 7
2 1 2 Oranges 222 1.12 2
2 1 3 Bananas 333 1.17 5
以下是我用来获取每张票的代码:
public OrderEntity getOrder(int orderId)
{
var data = from c in Orders
where c.OrderID == orderId
select c;
return data;
}
如何编写LINQ代码以合并2张票,以便获得数量的总和?看起来应该是这样......
订购门票#1和#2
CustomerID ItemID Description POS# Cost Quantity
1 1 Apples 111 1.25 10
1 2 Oranges 222 1.12 7
1 3 Bananas 333 1.17 10
似乎我应该能够做到这样......
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
select c;
return data.ToList();
}
问题是我无法弄清楚分组。有很多关于如何编写EF代码进行分组的信息,但是我不确定我是应该在CustomerID上还是在Quantity上进行分组。任何有关如何进行分组的提示都将非常感激。
答案 0 :(得分:2)
您应该按CustomerID
和ItemID
分组:
尝试这样的事情:
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
group c by new { c.CustomerID, c.ItemID } into g
select new OrderEntity () {
CustomerID = g.Key.CustomerID,
ItemID = g.Key.ItemID,
Quantity = g.Sum(x => x.Quantity)
};
return data.ToList();
}
我不确定您如何定义数据,但如果您需要在结果中使用Description
POS
,Cost
,请尝试:
public List<OrderEntity> getCustomerOrders(int customerId)
{
var data = from c in Orders
where c.CustomerID == customerId
group c by new { c.CustomerID, c.ItemID,c.Description,c.POST,c.Cost } into g
select new OrderEntity () {
CustomerID = g.Key.CustomerID,
ItemID = g.Key.ItemID,
Quantity = g.Sum(x => x.Quantity),
Description = g.Key.Description,
POST = g.Key.POST,
Cost = g.Key.Cost
};
return data.ToList();
}