简体   繁体   English

使用反射对多个属性进行 GroupBy 动态列表

[英]GroupBy dynamic list on multiple properties by using reflection

I have a class that defines some settings, one of this settings are the properties to group the list that you want to group by:我有一个 class 定义了一些设置,其中一个设置是对要分组的列表进行分组的属性:

object of class MySetting object 的 class 我的设置

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

Now I have a dynamic list and I want to send this list as parameter with object setting to a method like ApplySetting , this method has to check if Groupby not a null and group my list:现在我有一个动态列表,我想将此列表作为参数发送给 ApplySetting 之类的方法, settingApplySetting ,此方法必须检查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())))
   
  }
}

Note: GetPropertyValue is a method that get value from object by using reflection.注意: GetPropertyValue是一种使用反射从 object 中获取值的方法。
Thanks for any help.谢谢你的帮助。

This is not solution with reflection you asked for but hack, but maybe it can serve you.这不是您要求的反思解决方案,而是破解,但也许它可以为您服务。 It uses lib System.Linq.Dynamic.Core and converts list to Queriable.它使用 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);
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM