C# 如何订购通用列表<;T>;(当T是一个类时)通过它的一个属性?

C# 如何订购通用列表<;T>;(当T是一个类时)通过它的一个属性?,c#,list,generics,properties,C#,List,Generics,Properties,很简单,我不确定是否可能,而且我也找不到一个例子 void Order<T>(List<T> lista) { // get all properties, T is always a class List<PropertyInfo> props = typeof(T).GetProperties().ToList(); // just order by one property, let's say: props[0] Li

很简单,我不确定是否可能,而且我也找不到一个例子

void Order<T>(List<T> lista)
{
    // get all properties, T is always a class
    List<PropertyInfo> props = typeof(T).GetProperties().ToList();

    // just order by one property, let's say: props[0]
    List<T> oList = lista.OrderBy( /* props[0] */ );
}
无效订单(列表A)
{
//获取所有属性,T始终是一个类
List props=typeof(T).GetProperties().ToList();
//只需按一个属性排序,比如:道具[0]
List-oList=lista.OrderBy(/*props[0]*/);
}
只需要新的有序列表。

我认为这应该可以工作(如果属性数组不是空的)

List oList=lista.OrderBy(item=>props[0].GetValue(item)).ToList();
在Mono上,没有接受单个参数的GetValue重载

List<T> oList = lista.OrderBy(item => props[0].GetValue(item, null)).ToList();
List-oList=lista.OrderBy(item=>props[0].GetValue(item,null)).ToList();
使用来自的代码会产生以下结果:


它必须与生俱来IComparable@ThreeFx:请不要仅仅因为随机代码片段看起来对不懂该语言的人有用就提供它们。哪个属性不是问题,我稍后会得到它。我只是想知道是否可以按
props
@decPL的任何属性对列表排序。Thnx(我刚从问题中复制过来)
List<T> oList = lista.OrderBy(item => props[0].GetValue(item, null)).ToList();
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> entities, string propertyName)
{
    if (!entities.Any() || string.IsNullOrEmpty(propertyName))
        return entities;

    var propertyInfo = entities.First().GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    return entities.OrderBy(e => propertyInfo.GetValue(e, null));
}
lista.OrderBy(props[0].Name).ToList();