使用linq group by计算统计数据

时间:2018-04-04 16:01:08

标签: c# entity-framework linq

我正在尝试计算如下统计数据:

  

成功:10

     

失败:10

以下是我的表格:

public partial class MyProgress
    {
        public int Id { get; set; }
        public int JobId { get; set; }
        public int TestPartId { get; set; }
        public virtual TestPart TestPart { get; set; }
    }

    public partial class Job
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }

作业表包含如下记录:

Id       StateName
1        Failed
2        Succeeded

这就是我试图计算静电的方法:

var query = from p in context.MyProgress
             join job in context.Jobs on p.TestPartId equals job.Id
             where p.TestPart.Test.RegionId == 100
             group p by new
             {
                   p.TestPartId
             } into g
             select new
             {
                    succeeded = g.Sum(e => g.First(). ? 1 : 0),     
             }).FirstOrDefault();

但是在上面的查询中,我无法在计算成功和失败统计数据时获取StateName属性,因为我无法在group by的一部分中选择。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用group by对感兴趣的结果进行分组,然后计算(one)组中的每种类型:

$("#datepicker, #datepicker2").datepicker({
      showOtherMonths: true,
      selectOtherMonths: true
});

您也可以考虑另一种方式并找到感兴趣的var ans = from p in MyProgress where p.TestPart.RegionId == 100 join j in Jobs on p.TestPartId equals j.Id group j by 1 into jg select new { Succeeded = jg.Count(j => j.StateName == "Succeeded"), Failed = jg.Count(j => j.StateName == "Failed") }; ,但您仍然需要计算单个组:

job

注意:如果您可以获得包含每个州和一个计数的表格,您可以在var ans2 = from j in Jobs where (from p in MyProgress where p.TestPart.RegionId == 100 select p.TestPartId).Contains(j.Id) group j by 1 into jg select new { Succeeded = jg.Count(j => j.StateName == "Succeeded"), Failed = jg.Count(j => j.StateName == "Failed") }; 上进行分组:

StateName