LINQ分组数据两次

时间:2011-10-21 17:45:58

标签: c# linq group-by

为可怕的标题道歉,我不太确定如何说出我的问题。

我有一个看起来像的对象:

CustAcct cust = new CustAcct();
cust.Name = "John Doe";
cust.Account = "ABC123";
cust.OrderTotal = 123.43
cust.OrderQty = 4;
cust.TransDate = "12/26/2010 13:00"

请不要花太多时间批评下一部分,因为这真的不涉及购物车/顾客的东西,但想法是一样的,我只是想使用每个人都非常熟悉的东西。 / p>

一个帐户可以有多个客户,而一个客户可以拥有多个帐户。

所以你有:

List<CustAcct> custList = new List<CustAcct>();
custList.Add("John Doe", "ABC123", 123.43, 4, "12/26/2010 13:00");
custList.Add("John Doe", "ABC123", 32.12, 2, "12/27/2010 10:00");
custList.Add("John Doe", "ABC321", 43.34, 1, "12/28/2010 15:00");
custList.Add("John Doe", "ABC321", 54.60, 3, "12/28/2010 16:00");
custList.Add("Jane Zoe", "ABC123", 46.45, 2, "12/28/2010 17:00");
custList.Add("Jane Zoe", "ABC123", 32.65, 1, "12/29/2010 12:00");
custList.Add("Jane Zoe", "ABC321", 67.65, 3, "12/29/2010 23:00");
custList.Add("Jane Zoe", "ABC321", 75.34, 4, "12/30/2010 08:00");

我想要为每个帐户和客户获取所有OrderTotal和OrderQty的总和,以便我的输出如下:

Account    Customer    OrderTotal    OrderQty
 ABC123     John Doe    155.55          6
 ABC321     John Doe     97.94          4
 ABC123     Jane Zoe     79.10          3
 ABC321     Jane Zoe    142.99          7

我已经阅读了LINQ to Objects一书和101个LINQ样本,并且无法弄清楚如何获得这个。谢谢。

1 个答案:

答案 0 :(得分:9)

你可以这样分组和总结:

from ca in custList
group ca by new { ca.Name, ca.Account } into g
select new {
    g.Key.Account,
    g.Key.Name,
    OrderTotal = g.Sum(o => o.OrderTotal),
    OrderQty = g.Sum(o => o.OrderQty)
};

<强> See it in action