[英]LINQ GroupBy with a dynamic group of columns
我有一张这样的表:
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 实现这一目标?
重要提示:我已将问题简化为两个布尔变量( 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(...)
我可以在这里做这样的事情吗?
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()
});
如果您需要真正动态,请使用 Scott Gu 的Dynamic LINQ库。
您只需要弄清楚要包含在结果中的列并按它们分组。
public static IQueryable GroupByColumns(this IQueryable source,
bool includeVariety = false,
bool includeCategory = false)
{
var columns = new List<string>();
if (includeVariety) columns.Add("Variety");
if (includeCategory) columns.Add("Category");
return source.GroupBy($"new({String.Join(",", columns)})", "it");
}
然后你可以把它们分组。
var query = rows.GroupByColumns(includeVariety: true, includeCategory: true);
在任何情况下,仍然需要在没有动态 LINQ 和类型安全的情况下按动态列进行分组。 您可以为这个 IQueryable 扩展方法提供一个匿名对象,其中包含您可能想要分组的所有属性(具有匹配的类型!)以及您想要用于此组调用的属性名称列表。 在第一个重载中,我使用匿名对象来获取它的构造函数和属性。 我使用它们动态地按表达式构建组。 在第二个重载中,我仅将匿名对象用于 TKey 的类型推断,不幸的是,在 C# 中无法绕过,因为它的类型别名能力有限。
只适用于这样的可为空的属性,可能很容易扩展为不可空的属性,但现在不能打扰
public static IQueryable<IGrouping<TKey, TElement>> GroupByProps<TElement, TKey>(this IQueryable<TElement> self, TKey model, params string[] propNames)
{
var modelType = model.GetType();
var props = modelType.GetProperties();
var modelCtor = modelType.GetConstructor(props.Select(t => t.PropertyType).ToArray());
return self.GroupByProps(model, modelCtor, props, propNames);
}
public static IQueryable<IGrouping<TKey, TElement>> GroupByProps<TElement, TKey>(this IQueryable<TElement> self, TKey model, ConstructorInfo modelCtor, PropertyInfo[] props, params string[] propNames)
{
var parameter = Expression.Parameter(typeof(TElement), "r");
var propExpressions = props
.Select(p =>
{
Expression value;
if (propNames.Contains(p.Name))
value = Expression.PropertyOrField(parameter, p.Name);
else
value = Expression.Convert(Expression.Constant(null, typeof(object)), p.PropertyType);
return value;
})
.ToArray();
var n = Expression.New(
modelCtor,
propExpressions,
props
);
var expr = Expression.Lambda<Func<TElement, TKey>>(n, parameter);
return self.GroupBy(expr);
}
我实现了两个重载,以防您想缓存构造函数和属性以避免每次调用时进行反射。 像这样使用:
//Class with properties that you want to group by
class Record
{
public string Test { get; set; }
public int? Hallo { get; set; }
public DateTime? Prop { get; set; }
public string PropertyWhichYouNeverWantToGroupBy { get; set; }
}
//usage
IQueryable<Record> queryable = ...; //the queryable
var grouped = queryable.GroupByProps(new
{
Test = (string)null, //put all properties that you might want to group by here
Hallo = (int?)null,
Prop = (DateTime?)null
}, nameof(Record.Test), nameof(Record.Prop)); //This will group by Test and Prop but not by Hallo
//Or to cache constructor and props
var anonymous = new
{
Test = (string)null, //put all properties that you might want to group by here
Hallo = (int?)null,
Prop = (DateTime?)null
};
var type = anonymous.GetType();
var constructor = type.GetConstructor(new[]
{
typeof(string), //Put all property types of your anonymous object here
typeof(int?),
typeof(DateTime?)
});
var props = type.GetProperties();
//You need to keep constructor and props and maybe anonymous
//Then call without reflection overhead
queryable.GroupByProps(anonymous, constructor, props, nameof(Record.Test), nameof(Record.Prop));
您将作为 TKey 接收的匿名对象将仅填充您用于分组的密钥(即在此示例中为“Test”和“Prop”),其他的将为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.