[英]Linq query sum up the amount column
var result = (from t1 in _dbEntities.Charges
join t2 in _dbEntities.ChargesTypes on t1.ChargesTypeID equals t2.ID
where t1.StudentID == 1033
select new {t2.Amount}).SingleOrDefault();
I want to sum the amount
column how to do that and it should be convert into int
before sum it up 我想对amount
列进行汇总,并在汇总之前将其转换为int
Firstly, you're using SingleOrDefault
which will only select a single value. 首先,您使用的是SingleOrDefault
,它将仅选择一个值。 You want to use Sum
instead. 您想改用Sum
。 Also, you don't need an anonymous type here. 另外,您在这里不需要匿名类型。 You can just use: 您可以使用:
var result = (from t1 in _dbEntities.Charges
join t2 in _dbEntities.ChargesTypes on t1.ChargesTypeID equals t2.ID
where t1.StudentID == 1033
select (int) t2.Ammount).Sum();
Alternatively, you could use the form of Sum
which takes a projection, possibly using a different form of Join
as you only want the t2
value: 或者,您可以使用Sum
形式进行投影,也可以使用另一种Join
形式,因为您只需要t2
值:
var result = _dbEntities.Charges
.Join(_dbEntities.ChargesTypes,
t1 => t1.ChargesTypeID,
t2 => t2.ID,
(t1, t2) => t2)
.Sum(t2 => (int) t2.Ammount);
Or even convert in the join and use the "plain" Sum
afterwards: 甚至转换联接,然后使用“纯” Sum
:
var result = _dbEntities.Charges
.Join(_dbEntities.ChargesTypes,
t1 => t1.ChargesTypeID,
t2 => t2.ID,
(t1, t2) => (int) t2.Ammount)
.Sum();
EDIT: If the Ammount
column (which should be Amount
by the way) in the database is an NVARCHAR
then a) change it if you possibly can. 编辑:如果数据库中的Ammount
列(应为Amount
的方式)是NVARCHAR
则a)如果可以的话,将其更改。 Life is always simpler if the database types are appropriate; 如果数据库类型合适,则生活总是更简单; b) use int.Parse
if you can't: b)如果不能,请使用int.Parse
:
var result = (from t1 in _dbEntities.Charges
join t2 in _dbEntities.ChargesTypes on t1.ChargesTypeID equals t2.ID
where t1.StudentID == 1033
select int.Parse(t2.Ammount)).Sum();
If that doesn't work, you may need to do the parsing on the .NET side, eg 如果这样不起作用,则可能需要在.NET端进行解析,例如
var result = (from t1 in _dbEntities.Charges
join t2 in _dbEntities.ChargesTypes on t1.ChargesTypeID equals t2.ID
where t1.StudentID == 1033
select t2.Ammount)
.AsEnumerable() // Do the rest client-side
.Sum(x => int.Parse(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.