【问题标题】:Need help creating Linq.Expression to Enumerable.GroupBy需要帮助创建 Linq.Expression 到 Enumerable.GroupBy
【发布时间】:2010-12-11 15:26:12
【问题描述】:

我正在尝试生成一个表达式树,它最终在 Enumerable 类型上调用一系列 GroupBy 方法。

我正在尝试这样的简化形式:

IEnumerable<Data> list = new List<Data>{new Data{Name = "A", Age=10},
   new Data{Name = "A", Age=12},
   new Data{Name = "B", Age=20},
   new Data{Name="C", Age=15}};

Expression data = Expression.Parameter(typeof(IEnumerable<Data>), "data");
Expression arg = Expression.Parameter(typeof(Data), "arg");
Expression nameProperty = Expression.PropertyOrField(arg, "Name");

Expression group = Expression.Call(typeof(Enumerable), "GroupBy", new Type[] { typeof(Data), typeof(string) }, data, nameProperty);

最后对 Expression.Call 的调用会抛出“类型 'System.Linq.Enumerable' 上没有方法 'GroupBy' 与提供的参数兼容。”

我正在做类似的事情,以类似的方式与Enumerable.OrderBy 成功并被难住了。

感谢任何帮助。

【问题讨论】:

    标签: c# linq .net-3.5 linq-to-objects expression


    【解决方案1】:

    您不需要将 lambda 作为第二种类型传入吗?像这样。

        public void Test()
        {
            IEnumerable<Data> list = new List<Data>
            {
                new Data{Name = "A", Age=10},
                new Data{Name = "A", Age=12},
                new Data{Name = "B", Age=20},
                new Data{Name= "C", Age=15}
            };
    
    
            var data = Expression.Parameter(typeof(IEnumerable<Data>), "data");
            var arg = Expression.Parameter(typeof(Data), "arg");
            var nameProperty = Expression.PropertyOrField(arg, "Name");
            var lambda = Expression.Lambda<Func<Data, string>>(nameProperty, arg);
    
            var expression = Expression.Call(
                typeof(Enumerable),
                "GroupBy", 
                new Type[] { typeof(Data), typeof(string) },
                data,
                lambda);
    
            //expected = {data.GroupBy(arg => arg.Name)}
        }
    

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 2011-08-02
      • 2013-12-08
      • 1970-01-01
      • 2013-03-27
      • 2019-06-12
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多