[英]How can I return a object with the sum of all objects from a list using Linq?
如果我有一個名為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?
看起來像你想要的東西:
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>
當然。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.