Linq查询汇总金额列

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();

我想总结 amount 列如何做到这一点,它应该在总结之前转换为 int

首先,您使用的 SingleOrDefault 只会 select 一个值。您想改用 Sum 。此外,您在这里不需要匿名类型。您可以只使用:

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();

或者,您可以使用 Sum 的形式进行投影,可能使用不同形式的 Join 因为您只需要 t2 值:

var result = _dbEntities.Charges
                        .Join(_dbEntities.ChargesTypes,
                              t1 => t1.ChargesTypeID,
                              t2 => t2.ID,
                              (t1, t2) => t2)
                        .Sum(t2 => (int) t2.Ammount);

或者甚至在连接中转换并在之后使用 "plain" Sum:

var result = _dbEntities.Charges
                        .Join(_dbEntities.ChargesTypes,
                              t1 => t1.ChargesTypeID,
                              t2 => t2.ID,
                              (t1, t2) => (int) t2.Ammount)
                        .Sum();

编辑:如果数据库中的 Ammount 列(顺便说一句,应该是 Amount)是 NVARCHAR,那么 a) 如果可能的话,更改它。如果数据库类型合适,生活总是会更简单; 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();

如果这不起作用,您可能需要在 .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));