分组lambda

时间:2010-10-06 15:59:21

标签: linq c#-4.0 lambda

如果我有这样的结构:

Batch  Amount
76  495.4
76  975.75
76  25
76  442.46
77  1335.12
77  2272.37
77  34.5
77  496.99
77  360
77  13
77  594.6

我希望得到像

这样的东西
Batch  Amount
76    1938.61
77    5106.58

表达式应该如何?

我开始使用类似的东西:

batches.GroupBy(x => new { Batch = x.Batch, Amount = x.Amount });

但这并不是我想要的东西。帮助我做对。感谢

2 个答案:

答案 0 :(得分:5)

关闭。试试这个:

batches.GroupBy(x => x.Batch, x => x.Amount).Select(g => new {
    Batch = g.Key,
    Amount = g.Sum()
});

答案 1 :(得分:1)

查询将如下所示:

var bs = from s in batches
            group s by s.Batch into g
            select new { Batch = g.Key, Amount = g.Sum(p => p.Amount) };

虽然我不知道lambda等价物是什么

UPD:

Resharper有很多帮助! :)

var batches = bs .GroupBy(s => s.Batch).Select(
                g => new {Batch = g.Key, Amount = g.Sum(p => p.Amount)});