【问题标题】:how to sortby a given value a generic type list [duplicate]如何按给定值排序泛型类型列表[重复]
【发布时间】:2026-01-10 05:15:01
【问题描述】:

我想做的是这段代码

filtered = GetUserList().OrderBy(p => p.Name).ToList();

以一般的方式

public static List<T> sortBy<T>(string field, List<T>list)
{
    //list.OrderBy(p=>p.Equals(field)).ToList();
    //list = list.OrderBy(p => p.GetType().GetProperties().ToList().Find(d => d.Name.Equals(field))).ToList();
    return list;
}

有什么建议吗?

【问题讨论】:

  • 你有什么问题?
  • generic 在这里可能是错误的术语。从您的代码来看,您正在尝试通过作为字符串传递的属性对列表进行排序。
  • 我需要按给定值(字段)排序,但每次都不同,所以我需要以通用方式进行排序。所以我尝试为此目的创建 sortBy 方法,但它不起作用
  • 是的,ManfredRadlwimmer 就是这样
  • 我遇到了一个非常相似(虽然稍微复杂一点)的案例,我将其链接为副本。使用那里提供的代码,您应该能够找到解决此特定问题的方法。

标签: c# linq list generics


【解决方案1】:

如果这是您的唯一要求,一种快速的方法(而不是我链接的更复杂的方法)是通过反射访问属性。此扩展方法将为您提供所需的基础知识:

public static class EnumerablePropertyAccessorExtensions
{
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string property)
    {
        return enumerable.OrderBy(x => GetProperty(x, property));
    }

    private static object GetProperty(object o, string propertyName)
    {
        return o.GetType().GetProperty(propertyName).GetValue(o, null);
    }
}

Example on Fiddle

或者(稍微优化)像这样:

public static class EnumerablePropertyAccessorExtensions
{
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string property)
    {
        var prop = typeof(T).GetProperty(property);
        return enumerable.OrderBy(x => GetProperty(x, prop));
    }

    private static object GetProperty(object o, PropertyInfo property)
    {
        return property.GetValue(o, null);
    }
}

Example on Fiddle

然后可以像这样在任何IEnumerable&lt;&gt; 上调用此扩展方法:

filtered = GetUserList().OrderBy("Name").ToList();

但请注意,此实现并未真正优化或防错。如果这是您所需要的,您可能想要实现它。

【讨论】:

  • 不错的简单解决方案!
最近更新 更多