c# List<dynamic> 按字段排序


    public static List<dynamic> OrderByKey (this IList<dynamic> list, string propertyName, bool isDescending = false)
    {
        var propertyInfo = list[0].GetType().GetProperty(propertyName);
        if (isDescending)
        {
            return list.OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList();
        }
        else
        {
            return list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();
        }
    }


    public static List<T> OrderByKey<T>(this IList<T> list, string propertyName, bool isDescending = false)
    {
        var propertyInfo = typeof(T).GetProperty(propertyName);
        if (isDescending)
        {
            return list.OrderByDescending(x => propertyInfo.GetValue(x, null)).ToList();
        }
        else
        {
            return list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList();
        }
    }

posted @ 2025-09-25 13:27  Hey,Coder!  阅读(6)  评论(0)    收藏  举报