【问题标题】:Add Seperate Sum Functions to an IQueryable LINQ Statement将单独的 Sum 函数添加到 IQueryable LINQ 语句
【发布时间】:2011-01-18 16:00:07
【问题描述】:

我希望使用 IQueryable 数据源填充 Telerik RadGrid,但在该网格中包含 5 个 Total 列。当我创建单独的报表时,我已经为总计构建了单独的函数,但是在将它们迭代到我当前的网格 LINQ 语句中时遇到了一些问题。

我当前的 LINQ 语句如下所示:

public static IQueryable GetUnapprovedTimesheets(string Period)
    {
        DataContext Data = new DataContext();

        var Times = (from c in Data.System_Times
                     where c.Period == Period && c.Status == 1
                     orderby c.Employee.LName
                     select c).GroupBy(s => s.EmployeeID).Select(x => x.FirstOrDefault());

        return Times;
    }

此语句获取输入期间的时间表,并显示状态为 1 的记录,然后按 EmployeeID 分组显示。此语句将所有内容正确地拉入网格,但我还想添加常规、加班、旅行和子的总计。

我为动态报告单独构建的函数如下所示:

public static decimal? GetTotalReg(int EmployeeID, string Period)
    {
        DataContext Data = new DataContext();
        var Total = (from c in Data.Times
                     where c.EmployeeID == EmployeeID && c.Period == Period && c.PayCode == "211"
                     select c.Hours);

        return Total.Sum();
    }

有没有办法将第二个语句合并到第一个语句中? (请记住,我不仅要包含一个,还要包含 5 个 Sum 语句)

然后,这条语句将用作我的 RadGrid 的 IQueryable 数据源,由 RadGrid 的 DataField=" " 调用。

【问题讨论】:

    标签: c# linq iqueryable radgrid telerik-grid


    【解决方案1】:

    类似这样的:

    public static IQueryable GetUnapprovedTimesheets(string period)
    {
       DataContext data = new DataContext();
    
       var times = data
                       .Where(a => a.Period == period && a.Status == 1)
                       .OrderBy(a => a.Employee.LName)
                       .GroupBy(a => a.EmployeeID)
                       .Select(
                          a => new{
                                   System_Time = a.FirstOrDefault(),
                                   TotalReg = data.Times
                                               .Where(b => b.EmployeeID == a.Key 
                                                        && b.Period == period
                                                        && b.PayCode == "211")
                                               .Sum(b => b.Hours)
                                  }
                              );
    
       return times;
    }
    

    编辑: 抱歉,我刚刚注意到 GetTotalReg 调用使用了不同的实体。我会修改我的答案。

    更新: TotalReg 现在是从 data.Times 求和的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多