簡體   English   中英

如何使用Linq從列表中返回具有所有對象總和的對象?

[英]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>當然。)

我認為你可以用GroupBySum函數做到這一點

使用循環獲取此數據的示例可能如下所示:

foreach(var group in SpendlineList.GroupBy(x => x.Year))
{
   int year = group.Key;
   int ammount = group.Sum(x => x.Ammount);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM