linq 使用反射对多个属性创建GroupBy动态列表

fquxozlt  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个类,定义了一些设置,其中一个设置是属性分组列表,你想分组:
MySetting类的对象

MySetting setting = new()
{
 Groupby = $"{nameof(MyCss.Color)}, {nameof(MyCss.Width)}",
 //.....
}

现在我有了一个动态列表,我想把这个列表作为对象setting的参数发送给一个类似ApplySetting的方法,这个方法必须检查Groupby是否不为空,并对我的列表进行分组:

public ApplySetting(List<TItem> myList, MySetting setting)
{
  if(setting.Groupby != null)
  {
   var arr = setting.Groupby.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
    //do some this like, this wrong !
    var groubs = myList.GroupBy(x => arr.ForEach(y => GetPropertyValue(y, x, x.GetType())))
   
  }
}

注:GetPropertyValue是一个通过反射从对象获取值的方法。
谢谢你的帮助。

tktrz96b

tktrz96b1#

这不是你要求的反射解决方案,而是黑客,但也许它可以为你服务。它使用lib System.Linq.Dynamic.Core并将列表转换为可查询的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
        
public class MySetting {
    public string Groupby {get; set;}
}

public class ToGroupType{
    public string Color {get; set;}
    public string Width {get; set;}
}

public class Program
{
    public static void Main()
    {
        MySetting setting = new()
        {
         Groupby = $"Color, Width",
         //.....
        };
         static void  ApplySetting<TItem>(List<TItem> myList, MySetting setting)
        {
          if(setting.Groupby != null)
          {
           //do some this like, this wrong !
            var groubs = myList.AsQueryable().GroupBy($"new ({setting.Groupby})", "it").Select($"new (it.Key as Key , Count() as Count)").ToDynamicList();
            Console.WriteLine(string.Join(",", groubs));
            //result:  Key = { Color = Red, Width = 10 }, Count = 2 },{ Key = { Color = Blue, Width = 10 }, Count = 2 },{ Key = { Color = Blue, Width = 15 }, Count = 1 }
          }
        }
        ApplySetting(new List<ToGroupType>(){
            new ToGroupType{Color = "Red", Width="10"},
            new ToGroupType{Color = "Red", Width="10"},
            new ToGroupType{Color = "Blue", Width="10"},
            new ToGroupType{Color = "Blue", Width="10"},
            new ToGroupType{Color = "Blue", Width="15"},
            
        }, setting);
}}

相关问题