【问题标题】:GroupBy dynamic list on multiple properties by using reflection使用反射对多个属性进行 GroupBy 动态列表
【发布时间】:2023-01-13 03:59:36
【问题描述】:

我有一个定义一些设置的类,其中一个设置是用于对要分组的列表进行分组的属性:

MySetting 类的对象

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

现在我有一个动态列表,我想将此列表作为参数与对象 setting 一起发送到类似 ApplySetting 的方法,此方法必须检查 Groupby 是否为 null 并将我的列表分组:

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是一种通过反射从对象中获取值的方法。
谢谢你的帮助。

【问题讨论】:

    标签: c# linq asp.net-core


    【解决方案1】:

    这不是您要求的反思解决方案,而是 hack,但也许它可以为您服务。 它使用 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);
    }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 2011-05-13
      • 1970-01-01
      相关资源
      最近更新 更多