GroupBy,Sum和Count使用linq

时间:2015-10-22 09:16:45

标签: c# asp.net-mvc linq

我正在尝试获取吞吐量视图,我使用linq查询从MVC 5中的一个表计算一些统计信息。我需要按日期和计数以及某些列的总和对行进行分组

//模型

public class Assignment
{
    public int UserId { get; set; }
    public Datetime Modified {get; set; } 
    public double TimeSpent { get; set; }}
    public string date
    {
        get
        {
            return Modified.Date.ToString("d");
        }
    }
}

// controller

public ActionResult Throughputs()
{
    var records = db.Assignments.AsEnumerable(); 
    var groups = from r in records
                 group r by r.date
                 into row
                 select new ThroughputsViewModel
                 {
                     selectedDate = row.Key,
                     Total = row.Where(x => x.TimeSpent > 0).Select(x => x.UserId).Count(),
                     Total_Time = row.Sum(x => x.TimeSpent),
                     Rate = row.Where(x => x.TimeSpent > 0).Select(x => x.UserId).Count() / row.Sum(x => x.TimeSpent),
                     ResAssignments = row.AsEnumerable()
                 };
    return View(records);
}

//视图模型

public class ThroughputsViewModel
{
    public int Total { get; set; }
    public double Total_Time { get; set; }
    public double Rate { get; set; }
    public virtual User user { get; set;  }
    public int userId { get; set;  }
    public string selectedDate { get; set; }
    public IEnumerable<Assignment> ResAssignments { get; set; }
}

当我运行它时,我得到一个nullException或者行没有按照与原始表中相同的键进行分组,并且每行的sum和count值都是重复的

0 个答案:

没有答案