Linq-to-SQL gridview添加总和列

时间:2012-11-17 22:16:13

标签: c# asp.net linq-to-sql gridview

我在GridView中有这个linq查询

 var table = from ll in dbo.Workers
                    join p in dbo.WorkDays on ll.Id equals p.Id
                    orderby p.Enter
                    select new
                    {
                        ll.Id,
                        ll.Name,
                        ll.Salary,
                        p.Enter,
                        p.ExitT,
                        p.Place,
                        WorkTime = Math.Round(getWorkTime(p.Enter, p.ExitT), 2),
                        Earned = Math.Round(getEarned(p.Enter, p.ExitT, ll.Salary), 2),
                    };

如何在表格中添加总和列?

1 个答案:

答案 0 :(得分:1)

创建将保存数据并根据该数据提供计算的类:

public class WorkerInfo
{
    // I don't know exact type of fields, but its enough for you to get the idea
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public DateTime Enter { get; set; }
    public DateTime ExitT { get; set; }
    public string Place { get; set; }

    public int WorkTime
    {
       get { return (ExitT - Enter).TotalDays; }
    }

    public decimal Earned
    {
       get { return WorkTime * Salary; }
    }
}

用数据填写这些实体:

var workers = from ll in dbo.Workers
              join p in dbo.WorkDays on ll.Id equals p.Id
              orderby p.Enter
              select new WorkerInfo
              {
                 Id = ll.Id,
                 Name = ll.Name,
                 Salary = ll.Salary,
                 Enter = p.Enter,
                 ExitT = p.ExitT,
                 Place = p.Place
              }; 

更新用于返回所有日期的汇总数据的示例:

var query = from w in dbo.Workers
            join d in dbo.WorkDays on w.Id equals d.Id into days
            let WorkTime = days.Sum(d => d.ExitT - d.Enter)
            select new 
              {
                 w.Id,
                 w.Name,
                 w.Salary,
                 WorkTime,
                 Earned = WorkTime * w.Salary
              };