试图计算我的select语句

时间:2015-02-10 10:21:36

标签: linq lambda sum

我想用lambda将此语句重写为Linq语句。

var summe1 = (from l in db.Lg7s
    && new int[]{0,40}.Contains(l.REATE)
    && l.ANSWERING>0
    select (l.TALKINGTIME + l.ONHOLDTIME + l.ACTIONTIME + l.UPTIME)).Sum(i => i);

我试着这样做:

T4Number =  group
    .Where(lg => new int[]{38,40}.Contains(lg.CAUSE) && lg.ANSWERING>0)
    .Select(lg => new {DurationOfCallProcessing = lg.EN_ TALKINGTIME + lg.EN_ ONHOLDTIME + lg.EN_ ACTIONTIME + lg.UPTIME })
    .Sum()

但是,ide说,Sum不是有效的。

2 个答案:

答案 0 :(得分:0)

你不能"总和"匿名类型。我想你想要:

T4Number =  group
    .Where(lg => new int[]{38,40}.Contains(lg.CAUSE) && lg.ANSWERING>0)
    .Select(lg => new {DurationOfCallProcessing = lg.EN_ TALKINGTIME + lg.EN_ ONHOLDTIME + lg.EN_ ACTIONTIME + lg.UPTIME })
    .Sum(x => x.DurationOfCallProcessing);

但如果您只想要总和,则根本不需要创建anonymos类型:

T4Number =  group
    .Where(lg => new int[]{38,40}.Contains(lg.CAUSE) && lg.ANSWERING>0)
    .Sum(lg => lg.EN_ TALKINGTIME + lg.EN_ ONHOLDTIME + lg.EN_ ACTIONTIME + lg.UPTIME);

答案 1 :(得分:0)

尝试不使用匿名类型:

var causes = new [] { 38, 40 };

T4Number =  group
    .Where(lg => causes.Contains(lg.CAUSE) && lg.ANSWERING>0)
    .Select(lg => lg.EN_ TALKINGTIME + lg.EN_ ONHOLDTIME + lg.EN_ ACTIONTIME + lg.UPTIME })
    .Sum()

这也改善了过滤谓词不再是每次new的原因