如何制作Linq总和

时间:2010-10-25 15:41:31

标签: c# linq

我遇到LINQ表达式问题。

使用这个课程:

class MyClass
{
    public string of { get; set; }
    public string order { get; set; }
    public int qty { get; set; }

    public override string ToString()
    {
        return string.Format("OF: {0}, Order: {1}, Qty: {2}", of, order, qty);
    }
}

我希望通过OF和ORDER对所有数量求和 有了这些数据:

 var list = new List<MyClass>();
 list.Add(new MyClass { of = "of1", order = "order1", qty = 1 });
 list.Add(new MyClass { of = "of1", order = "order1", qty = 9 });
 list.Add(new MyClass { of = "of2", order = "order1", qty = 30 });
 list.Add(new MyClass { of = "of1", order = "order2", qty = 100 });

它应该返回

OF: of1, Order: order1, Qty: 10
OF: of2, Order: order1, Qty: 30
OF: of3, Order: order2, Qty: 100

我有这个解决方案,但我不喜欢它

 var sum = from p in list
                  group p by p.of+","+p.order
                  into g
                  select new MyClass
                             {
                                 of = g.Key.Split(',')[0],
                                 order = g.Key.Split(',')[1],
                                 qty = g.Sum(p=>p.qty)
                             };

1 个答案:

答案 0 :(得分:2)

您可以使用匿名类型作为密钥:

 var sum = from p in list
                  group p by new { Of = p.of, Order = p.order }
                  into g
                  select new MyClass
                             {
                                 of = g.Key.Of,
                                 order = g.Key.Order,
                                 qty = g.Sum(p=>p.qty)
                             };