如何对一个泛型 List<T>(其中 T 是一个类)按照其属性之一进行排序?

3

这是一个比较简短的内容,我不确定是否可行,而且我找不到例子。

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] */ );
}

只想要新的有序列表。


它必须继承IComparable。 - liran63
4
请不要随意提供代码片段,因为它们看起来可能适用于不懂该语言的人。 - Jon
哪个属性不是问题,我稍后会解决。我只想知道是否可以按props的任何属性对列表进行排序。 - Shin
2个回答

2

使用这篇博客中的代码将产生以下扩展方法

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();

1
我认为这应该有效(如果属性数组不为空)
List<T> oList = lista.OrderBy(item => props[0].GetValue(item)).ToList();

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

1
@decPL 我忘记加上ToList()了。谢谢(我只是从问题中复制过来的) - Dennis_E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接