Linq:使用表达式树语法按多列分组 [英] Linq: Group by multiple columns using Expression-tree syntax

查看:201
本文介绍了Linq:使用表达式树语法按多列分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改以下代码,以便处理多个属性的分组

I would like to change the following code so as to handle grouping of more than 1 property

private Expression<Func<ProfileResultView, string>> DynamicGroupBy(string propertyName)
{
    var parameterExp = Expression.Parameter(typeof(ProfileResultView), "x");
    var memberExp = Expression.PropertyOrField(parameterExp, propertyName);
    return Expression.Lambda<Func<ProfileResultView, string>>(memberExp, parameterExp);
}

所以这将被翻译为

GroupBy(x => new { x.Column1, x.Column2 })

如何用表达式树语法编写匿名类型?

how can I write the anonymous type in the expression-tree syntax?

推荐答案

如果分组键的类型对您而言并不重要,则可以动态创建类型并基于这些类型调用分组:

If the type of the grouping key does not matter for you, you can create types dynamically and call the grouping based on those types:

public static Expression<Func<TSource, object>> DynamicGroupBy<TSource>
       (params string[] properties)
{
    var entityType = typeof(TSource);
    var props = properties.Select(x => entityType.GetProperty(x)).ToList();
    var source = Expression.Parameter(entityType, "x");

    // create x=> new myType{ prop1 = x.prop1,...}
    var newType = CreateNewType(props);
    var binding = props.Select(p => Expression.Bind(newType.GetField(p.Name), 
                  Expression.Property(source, p.Name))).ToList();
    var body = Expression.MemberInit(Expression.New(newType), binding);
    var selector = Expression.Lambda<Func<TSource, object>>(body, source);
   return selector;
}
public static Type CreateNewType(List<PropertyInfo> props)
{
   AssemblyName asmName = new AssemblyName("MyAsm");
   AssemblyBuilder dynamicAssembly = AssemblyBuilder
       .DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
   ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAsm");
   TypeBuilder dynamicAnonymousType = dynamicModule
       .DefineType("MyType", TypeAttributes.Public);

   foreach (var p in props)
   {
       dynamicAnonymousType.DefineField(p.Name, p.PropertyType, FieldAttributes.Public);
   }
   return dynamicAnonymousType.CreateType();
}

请注意,组密钥类型为object.

Note that the group key type is object.

这篇关于Linq:使用表达式树语法按多列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆