LINQ:不同元素的Sum()

时间:2017-05-22 11:05:08

标签: c# linq

给出以下列表:

(TABLE1)
Expedient Amount 
1         10
1         10 
2         3
2         3
3         4

我想计算不同权宜之计'数量'的总和。所以总和应该是:

10 (from Expedient 1) + 
 3 (from Expediente 2) + 
 4 (from Expedient 3) = 
10 + 3 + 4 = 17

与此SQL句子类似的东西:

Select SUM(Amount) from 
(Select Distinct Expedient, Amount from TABLE1) DummyTable

3 个答案:

答案 0 :(得分:4)

在我的头顶,这样的事情应该可以解决问题:

TABLE1
    .GroupBy(t => new {t.Expedient, t.Amount})
    .Select(g => g.FirstOrDefault())
    .Sum(item => item.Amount);

答案 1 :(得分:0)

消费者的解决方案很明显。如果你想要更紧凑(那就是LINQ是什么),请使用GroupBy的重载:

Table1.GroupBy(t => new {t.Expedient, t.Amount}, (t, g) => g.First()).Sum(g => g.Amount)

答案 2 :(得分:0)

尝试代码:

 var result = (from p in tabledetails.AsEnumerable()
                      group p by p.id into jj
                      select new table1
                      {
                          id = jj.FirstOrDefault().id,
                          value = jj.ToList().Max(c => c.value)
                      }).ToList().Sum(c => c.value);