【问题标题】:Calculate statistics using linq group by使用 linq group by 计算统计信息
【发布时间】:2018-04-05 03:09:49
【问题描述】:

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

成功: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 属性,因为我无法选择分组依据的一部分。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 想要失败和成功的数量吗?或者您还需要其他信息吗?
  • @maccettura 只想要失败和成功的数量
  • 投反对票的人请至少评论一下这个问题中缺少的内容,所以我会在发布下一个问题时记住。谢谢:)
  • group by 创建一个新对象。使用 p.TestPartId 代替:group p by p.TestPartId,如果你只是成功和失败的状态,那么也许使用布尔值 HasSucceeded 代替。或者枚举也可以。
  • 为什么TestPartId 匹配job.Id 而不是JobId?为什么需要引用 MyProgress 来计算 Jobs 的总统计信息?

标签: c# entity-framework linq


【解决方案1】:

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

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")
          };

你也可以换个思路,找到感兴趣的jobs,但还是需要单组才能算:

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 上分组:

var ans3 = from p in MyProgress
           where p.TestPart.RegionId == 100
           join j in Jobs on p.TestPartId equals j.Id
           group j by j.StateName into jg
           select new {
               StateName = jg.Key,
               Count = jg.Count()
           };

【讨论】:

  • 非常感谢您为帮助我所做的努力。感谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 2012-04-10
  • 2012-08-29
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多