如何在Lambda表达式中计算/求和

时间:2010-04-29 17:17:56

标签: linq-to-sql

我需要将以下TSQL查询转换为Lambda,并且卡在Count和Sum上。我知道我可以在表达式的末尾添加.Count()和.Sum - 但是如何将值作为表达式的一部分?

T-SQL:

select b.pk, b.CreateTime, b.StartTime, b.endTime, count(a.rowid) as total, 
  sum(case when ItemStatus = 'success' then 1 else 0 end) as Sucess from... group by...

到目前为止我的表达:

var results = from context1 in dmbl1 join context2 in dmbl2 on context1.BatchLog_ID equals context2.pk
                      select new
                      {
                          CycleID = context2.pk,
                          CreateDateTime = context2.CreateDateTime,
                          StartTime = context2.startTime,
                          endTime = context2.endTime,
                          total = context1.RowID.   <<<<< This is where I need Countof
                          Success = <<< This is where I need Sumof
                      };

1 个答案:

答案 0 :(得分:1)

我弄清楚了,但不确定这是否是最好的处理方法;

如果有人找到更好的方法 - 意味着在单个表达中进行,请回复!!!

我将calc函数发送给方法;

var results = from Context1 in dmbl1.Table
                      join Context2 in dmbl2.batchLogs on Context1.BatchLog_ID equals Context2.pk
                      select new
                      {
                          CycleID = Context2.pk,
                          CreateDateTime = Context2.CreateDateTime,
                          StartTime = Context2.startTime,
                          endTime = Context2.endTime
                      };


        foreach (var result in results)
        {
            BatchJob bj = new BatchJob();
            bj.CreationDate = result.CreateDateTime;
            bj.CycleID = result.CycleID;
            bj.EndTime = result.endTime;
            bj.StartTime = result.StartTime;
        // From Here I called Methods that returned my counts 
            bj.TotalProcessed = Total(result.CycleID);
            bj.ProcessedSuccess = Success(result.CycleID);
            bj.ProcessedFailed = Failure(result.CycleID);
            batchjobs.Add(bj);
        }

私有Int32成功(int ID)         {             ...

        var success = (from blah in context1.table
                      where context1.ID == ID 
                      && context1.ItemStatus == "success"
                      select S context1.ItemStatus
                      ).Count();


        return success;
    }