Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Linq返回包含列表中所有对象总和的对象?_C#_Linq - Fatal编程技术网

C# 如何使用Linq返回包含列表中所有对象总和的对象?

C# 如何使用Linq返回包含列表中所有对象总和的对象?,c#,linq,C#,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

如果我有一个名为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
,当然可以获得
列表)。

看起来您想要的是:

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
,以获得
列表。

我认为您可以使用和函数来实现这一点

使用循环获取此数据的示例可能如下所示:

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

我认为您可以使用和函数来实现这一点

使用循环获取此数据的示例可能如下所示:

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