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,我有一个视频游戏的游戏列表: public class VideoGame{ public string Title; public string Platform; public string PublishingCompany; public int InStock; //this is how many that we have in stock public decimal Price; public int GameID; //this is the

我有一个视频游戏的游戏列表:

public class VideoGame{
   public string Title;
   public string Platform;
   public string PublishingCompany;
   public int InStock; //this is how many that we have in stock
   public decimal Price;
   public int GameID; //this is the ID of a specific title. For example: all DOOM games have   id of say 234 regardless of platform.
   //etc.
}
我想通过LINQ的简单求和查询,得到某款游戏的总库存量

我试过:

int stock = ListOfGames.Sum(e=>e.InStock == GameID); 
//GameID is a param that refers to the id of the game.
但这并没有返回正确的值

我看了这个问题:,但没有帮助。关于如何计算某个游戏ID的所有库存游戏数量的总和,你有什么想法吗?

你肯定需要

var sumOfStock = ListOfGames.Sum(vg => vg.InStock);
由于InStock是您希望合计的财产?

以下是我的建议:

int stock = ListOfGames.Where(e => e.GameID == GameID).Sum(e => e.InStock);

在您的查询中,您将InStock中的库存游戏数量与GameID参数进行比较,我相信这不是您想要做的

要获得所有库存游戏的总和,请执行以下操作:

int stock = ListOfGames.Sum(e=>e.InStock); 
但是,看起来您还想按特定游戏进行筛选?在这种情况下,GameID如何对应于您的视频游戏对象?如果在视频游戏类中有一个实际的ID字段,则可以得到如下的总和:

int stock = ListOfGames.Where(e=>e.ID == GameID).Sum(e=>e.InStock); 

如果要查询InStock等于特定GameId的所有视频游戏的总和,请尝试:

 var query = from game in ListOfGames
                  where game.InStock == GameId
                  select game;
 int sum = query.Sum();

我可能遗漏了一些东西,但InStock不太可能与Gameids匹配。那么,你真的不想知道所有库存游戏的数量之和吗?问题已被编辑。抱歉搞混了。但这总结了所有游戏,而不是OP要求的带有特殊GameID的游戏。我没能从问题文本中理解OP要求的。
int stock = ListOfGames.Where(e => e.GameId == GameID).Sum(e => e.InStock);
 var query = from game in ListOfGames
                  where game.InStock == GameId
                  select game;
 int sum = query.Sum();