Func<T, object> 选择器使用

感觉有点类似于委托,在一开始先绑定,到后面使用LINQ语句时再触发(不知道是不是这样,先记录一下)

 

public static void Main()
    {
        List<int> numbers = new List<int>() {10, 20, 30, 40, 50};
        
        // 创建一个 Func<T, object> 来获取大于20的元素
        Func<int, bool> selector = (num) => num > 20;
        
        // 使用 LINQ 的 Where 方法应用该选择器
        var result = numbers.Where(selector);
        
        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
    }

输出 :30  40  50

    // 使用 LINQ 进行多个分组的动态分组的方法
        public  static IEnumerable<IGrouping<object, ScmPurbillDtl>> GroupByDynamicProperties(List<ScmPurbillDtl> people, List<string> propertyNames)
        {
            // 利用反射获取属性信息
            var propertyInfos = propertyNames.Select(p => typeof(ScmPurbillDtl).GetProperty(p)).ToArray();

            // 使用匿名类型作为分组的键
            var keySelector = CreateKeySelector(propertyInfos, propertyNames);

            // 使用 LINQ 进行多个分组的动态分组
            var groupedPeople = people.GroupBy(keySelector);
            return groupedPeople;
        }

        // 创建匿名类型的选择器
        public static Func<ScmPurbillDtl, object> CreateKeySelector(PropertyInfo[] propertyInfos, List<string> propertyNames)
        {

            return person =>
            {
                int i = 0;
                // 创建匿名类型的实例
                var key = new
                {
                    Flowid = propertyInfos[i++].GetValue(person, null),
                    Vendorid = propertyInfos[i++].GetValue(person, null),
                    Balancetype = propertyInfos[i++].GetValue(person, null),
                    Logicwarehouseid = propertyInfos[i++].GetValue(person, null),
                    Hdrid = propertyNames.Contains("Hdrid") ? propertyInfos[i++].GetValue(person, null) : "",
                    Valuename = propertyNames.Contains("Valuename") ? propertyInfos[i++].GetValue(person, null) : "",
                };

                return key;
            };
        }

 

posted @ 2024-01-26 09:20  越吃越瘦  阅读(26)  评论(0编辑  收藏  举报