You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改LINQ查询,实现区域ALL且类别出现3次时的网格平均值展示

LINQ查询修改:新增分组平均值计算逻辑

现有查询代码

var resultData = from audit in _context.audittable
                  join region in _context.Regions on audit.RegionCode equals region.RegionCode
                  where audit.SearchDate >= loieStartDate && audit.SearchDate <= loieEndDate
                  select new SearchCriteriaAuditDTO()
                  {
                      AuditId = audit.DbLagTestSearchCriteriaAuditId, // 网格中隐藏的主键
                      SearchDate = audit.SearchDate.ToShortDateString(), // 日期列,网格仅重命名
                      OverAllAvgLagDays = audit.OverAllAvgLagDays, // 绑定网格字段,仅修改名称
                      RegionName = region.RegionName, // 关联表字段,audit表外键
                      CategoryId = Convert.ToInt32(audit.CategoryId), // 枚举ID,网格匹配显示
                  };

修改需求

现有查询返回的表格中,需新增以下逻辑:

  • 筛选出RegionName为"ALL"的记录
  • 对这些记录按CategoryId分组,仅保留分组内记录数≥3的分组
  • 计算每个符合条件分组的OverAllAvgLagDays平均值
  • 将这些平均值结果作为新行加入最终的网格数据集中

实现代码

// 1. 获取原始查询数据
var originalData = (from audit in _context.audittable
                    join region in _context.Regions on audit.RegionCode equals region.RegionCode
                    where audit.SearchDate >= loieStartDate && audit.SearchDate <= loieEndDate
                    select new SearchCriteriaAuditDTO()
                    {
                        AuditId = audit.DbLagTestSearchCriteriaAuditId,
                        SearchDate = audit.SearchDate.ToShortDateString(),
                        OverAllAvgLagDays = audit.OverAllAvgLagDays,
                        RegionName = region.RegionName,
                        CategoryId = Convert.ToInt32(audit.CategoryId),
                    }).ToList();

// 2. 筛选并计算符合条件的分组平均值
var avgAggregatedData = originalData
    .Where(d => d.RegionName == "ALL")
    .GroupBy(d => d.CategoryId)
    .Where(g => g.Count() >= 3)
    .Select(g => new SearchCriteriaAuditDTO()
    {
        AuditId = -1, // 用特殊值标记为聚合行,网格中隐藏
        SearchDate = "平均值", // 日期列显示聚合标识
        OverAllAvgLagDays = g.Average(d => d.OverAllAvgLagDays),
        RegionName = "ALL",
        CategoryId = g.Key,
    }).ToList();

// 3. 合并原始数据与聚合数据
var resultData = originalData.Concat(avgAggregatedData).ToList();

代码说明

  • 先执行原始查询获取基础数据并转为本地列表,方便后续分组计算
  • 筛选出RegionName为"ALL"的记录,按CategoryId分组后过滤出记录数≥3的分组,计算每组平均值并构造DTO
  • 用Concat合并原始数据和聚合数据,最终返回给网格展示
  • 聚合行的AuditId设为-1(可根据实际业务调整),确保网格隐藏该字段;SearchDate设为"平均值"用于标识聚合行

内容的提问来源于stack exchange,提问作者Farhin Shaikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 09:47:19