我有这样一个表格:
variety category quantity
----------------------------------------------
rg pm 10
gs pm 5
rg com 8
我希望根据以下两个bool
类型参数进行分组: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实现这个?
重要提示:我已将问题简化为 两个布尔变量 (IncludeVariety
和 IncludeCategory
) ,但实际上我将拥有更多的列 (比如说五个)
我想不出如何动态生成查询(使用.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(...)
我是否可以在这里做类似的事情?
Category = includeCategory ? r.Category : null, CategoryId = includeCategory ? r.CategoryId : (long?)null
-- 需要那个(long?)null
。 - sports