需要试下一个list动态分组功能,分组字段是多个并且是不确定的,求表达式生成方式。代码如下
1.实体定义
public class House { public string Name { get; set; } public string Month { get; set; } public int DfFee { get; set; } public int SfFee { get; set; } }
2.单条件动态分组
List<House> list = new List<House>(); list.Add(new House { Name = "张三", Month = "2017-01", DfFee = 100, SfFee = 20 }); list.Add(new House { Name = "张三", Month = "2017-02", DfFee = 20, SfFee = 100 }); list.Add(new House { Name = "张三", Month = "2017-03", DfFee = 10, SfFee = 40 }); list.Add(new House { Name = "李四", Month = "2017-01", DfFee = 67, SfFee = 24 }); list.Add(new House { Name = "李四", Month = "2017-04", DfFee = 672, SfFee = 243 }); var type = typeof(House); var parameter = Expression.Parameter(type, "e"); var propertyReference = Expression.Property(parameter, "Name");//根据Name分组 var func = Expression.Lambda<Func<House, dynamic>> (propertyReference , new[] { parameter }).Compile(); foreach (var item in list.GroupBy(func)) { Console.WriteLine(item.Key); }
上述代码可以根据House的任何属性进行分组
3.现在我想生成 list.GroupBy(e => new { e.Name, e.Month });动态表达式,请问该怎么写
Dynamic linq
https://dynamiclinq.codeplex.com/SourceControl/latest#DynamicLinq/System.Linq.Dynamic/Dynamic.cs
var query = list.AsQueryable() .GroupBy(string.Format("new ({0}, {1})", "Name", "Month"), "it") .Select("new(it.Key as Key, it as Houses)"); var groupList = (from dynamic g in query select g).ToList(); foreach (var g in groupList) { g.Key.Name, g.Key.Month; foreach (var h in g.Houses) // h.Name
list.GroupBy(string.Format("new ({0})", string.Join(",", allDimentsion)), "new(it as Vm)") as IEnumerable<IGrouping<dynamic, dynamic>>;
你好,我想问一下 list.GroupBy(string.Format("new ({0})", string.Join(",", allDimentsion)), "new(it as Vm)") as IEnumerable<IGrouping<dynamic, dynamic>>;
红色字体部分中的it和Vm是什么意思,为什么我用的时候提示是这样的?
参照 http://www.cnblogs.com/yanweidie/p/6485957.html
请参照这个文章,有详细介绍
@焰尾迭: O(∩_∩)O谢谢