如果我有一个名为Spendline的对象列表,其中包含两个属性Year,Amount和BudgetID。我怎样才能最好地转换以下列表:
Year Amount BudgetID
2000 100 1
2001 100 1
2002 100 1
2003 100 1
2001 100 2
2002 100 2
2003 100 2
对此:
Year Amount
2000 100
2001 200
2002 200
2003 200
使用Linq?
答案 0 :(得分:4)
看起来像你想要的东西:
var query = items.GroupBy(x => x.Year, x => x.Amount)
.Select(g => new { Year = g.Key, Amount = g.Sum() };
或者作为查询表达式:
var query = from item in items
group item.Amount by item.Year into g
select new { Year = g.Key, Amount = g.Sum() };
(在查询上调用ToList
以获得List<T>
当然。)
答案 1 :(得分:0)