Linq查询总结了数量列

Mik*_*ike 1 c# linq lambda entity-framework

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();
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 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();
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

编辑:如果数据库中的Ammount列(应该是Amount顺便)是a,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();
Run Code Online (Sandbox Code Playgroud)

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