Linq查询总结了数量列

时间:2015-01-31 14:42:09

标签: c# linq entity-framework lambda

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

1 个答案:

答案 0 :(得分:5)

首先,您使用SingleOrDefault,它只会选择一个值。您想要使用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);

甚至可以在联接中转换并在之后使用“普通”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));