我需要实现这样的目标,但我无法想象如何使其发挥作用:
class Program
{
static List<dynamic> myList = new List<dynamic>();
static void Main(string[] args)
{
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test1", Test2 = "test2" });
// I need to pass a dynamic list of expression like:
GenerateGroup<dynamic>(x=>x.Test, x => x.Test2); //groups myList in 2 groups
GenerateGroup<dynamic>(x=>x.Test2); //groups myList in a single group
}
private static void GenerateGroup<T>(params Expression<Func<T, object>>[] properties)
{
//I need to group for the properties passed as parameters
var result= myList.GroupBy(properties);
}
}
我收到编译错误:
表达式树可能不包含动态操作
这只是复杂应用程序的一个示例,但最后,我需要使用动态列表,我需要使用动态的属性列表对它们进行分组。这是因为我从多个PDF源读取数据/属性,并且不可能使用静态类。
是否可以修复此错误或者是编译器限制,我需要以另一种方式解决问题?
更新
由于你的回答,我认为我向前迈出了一步:
class Program
{
static List<dynamic> myList = new List<dynamic>();
static List<Foo> myListFoo = new List<Foo>();
static void Main(string[] args)
{
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test1", Test2 = "test2" });
myListFoo.Add(new Foo { MyProperty =1});
GenerateGroup<dynamic>(x =>new { x.Test, x.Test2});
GenerateGroup<Foo>(x=>x.MyProperty);
}
private static void GenerateGroup<T>(Func<T, object> properties)
{
var result= myList.GroupBy(properties);
result = myListFoo.GroupBy(properties);
}
}
public class Foo
{
public int MyProperty { get; set; }
}
我在groupBy上只有编译错误:
'
List<dynamic>
'不包含'GroupBy'的定义,而最佳扩展方法重载'ParallelEnumerable.GroupBy<T, object>
(ParallelQuery<T>, Func<T, object>
)'需要类型为'ParallelQuery<T>
的接收器“
答案 0 :(得分:2)
您需要对代码进行一些更改:
Expression<Func<,>>
不是您要找的,Where
所接受的IEnumerable<T>
重载全部使用Func<,>
GenerateGroup
dynamic
通用
如果你混合所有这些点,你应该得到这样的结果:
static void Main(string[] args)
{
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test", Test2 = "test2" });
myList.Add(new { Test = "test1", Test2 = "test2" });
// I need to pass a dynamic list of expression like:
GenerateGroup(x => new { x.Test, x.Test2 } ); //groups myList by Test and Test2
GenerateGroup(x => x.Test2); //groups myList in a single group
}
private static void GenerateGroup(Func<dynamic, object> groupper)
{
var groupped = myList.GroupBy(groupper);
}