c# - 具有动态列组的 LINQ GroupBy

标签 c# linq group-by

我有一个这样的表:

 variety category  quantity
----------------------------------------------
  rg      pm         10
  gs      pm          5
  rg      com         8

我想根据这些 bool 参数创建一个 GroupBy:

  • IncludeVariety
  • IncludeCategory

例如:

IncludeVariety = true;
IncludeCategory = true;

会返回这个:

 variety category  quantity
----------------------------------------------
  rg      pm         10
  gs      pm          5
  rg      com         8

还有这个:

IncludeVariety = true;
IncludeCategory = false;

会返回这个:

  variety category  quantity
----------------------------------------------
    rg      -         18
    gs      -          5

还有这个:

IncludeVariety = false;
IncludeCategory = true;

会返回这个:

  variety category  quantity
----------------------------------------------
     -      pm         15
     -      com         8

你明白了......

问题:如何使用 LINQ 实现此目的?

重要:我已将问题简化为两个 bool 变量(IncludeVarietyIncludeCategory)但在实际上我会有更多专栏(比如五个)

我不知道如何动态生成查询(.GroupBy.Select):

 rows.GroupBy(r => new { r.Variety, r.Category })
 .Select(g => new 
  {
        Variety = g.Key.Variety,
        Category = g.Key.Category,
        Quantity = g.Sum(a => a.Quantity),
  });

 rows.GroupBy(r => new { r.Category })
 .Select(g => new 
  {
        Variety = new {},
        Category = g.Key.Category,
        Quantity = g.Sum(a => a.Quantity),
  });

 rows.GroupBy(r => new { r.Variety })
 .Select(g => new 
  {
        Variety = g.Key.Variety,
        Category = new {},
        Quantity = g.Sum(a => a.Quantity),
  });

我过去做过的类似事情是连接Where,例如:

  var query = ...

  if (foo) {
       query = query.Where(...)
  }

  if (bar) {
       query = query.Where(...)
  }

  var result = query.Select(...)

我可以在这里做类似的事情吗?

最佳答案

var results=items
  .Select(i=>
    new {
      variety=includevariety?t.variety:null,
      category=includecategory?t.category:null,
      ...
    })
  .GroupBy(g=>
    new { variety, category, ... }, g=>g.quantity)
  .Select(i=>new {
    variety=i.Key.variety,
    category=i.Key.category,
    ...
    quantity=i.Sum()
  });

缩短:

var results=items
  .GroupBy(g=>
    new {
      variety=includevariety?t.variety:null,
      category=includecategory?t.category:null,
      ... 
    }, g=>g.quantity)
  .Select(i=>new {
    variety=i.Key.variety,
    category=i.Key.category,
    ...
    quantity=i.Sum()
  });

关于c# - 具有动态列组的 LINQ GroupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33286297/

相关文章:

c# - 如何定义类型为 T 的类属性

c# - 如何计算积分?

MySQL 使用 AND 语句查找重复记录

sql - 将多行合并为一个

c# - 文件名模式在 OpenFileDialog 中不起作用

c# - 使用mvvm动态创建控件

c# - 使用 Linq 和 Lambda 包含默认值

c# - 从列表中按 ID 选择

sql - Postgres GROUP BY 查看日期范围

c# - 构造具有不同输出的 C# 代码,唯一的区别应该是 Nullable<int> 与 int?