我有一个List ListOfGames,其中VideoGame是:
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.
但是没有返回正确的值。
我看了这个问题:Sum properties using LINQ,但它没有帮助。关于如何获得特定GameID的所有游戏库存数量总和的任何想法?
答案 0 :(得分:5)
int stock = ListOfGames.Where(x=>x.Id == GameID).Sum(x=>x.Instock);
答案 1 :(得分:4)
这是我的建议:
int stock = ListOfGames.Where(e => e.GameID == GameID).Sum(e => e.InStock);
答案 2 :(得分:2)
当然你只是需要
var sumOfStock = ListOfGames.Sum(vg => vg.InStock);
因为InStock
是您想要求和的属性吗?
答案 3 :(得分:2)
在您的查询中,您将库存中的游戏数量(InStock)与GameID参数进行比较,我确定这不是您想要的。
获得现货中所有游戏的总和:
int stock = ListOfGames.Sum(e=>e.InStock);
但是,看起来您还希望按特定游戏进行过滤?在这种情况下,GameID如何与您的VideoGame对象相对应?如果你在VideoGame类上有一个实际的ID字段,你可以得到这样的总和:
int stock = ListOfGames.Where(e=>e.ID == GameID).Sum(e=>e.InStock);
答案 4 :(得分:1)
int stock = ListOfGames.Where(e => e.GameId == GameID).Sum(e => e.InStock);
答案 5 :(得分:0)
如果您想查询VideoGame
等于特定InStock
的所有GameId
的总和,请尝试:
var query = from game in ListOfGames
where game.InStock == GameId
select game;
int sum = query.Sum();