如何基于T的属性对List<T>进行排序?

15

我的代码长这样:

Collection<NameValueCollection> optionInfoCollection = ....
List<NameValueCollection> optionInfoList = new List<NameValueCollection>();
optionInfoList = optionInfoCollection.ToList();

if(_isAlphabeticalSoting)
   Sort optionInfoList

我尝试了 optionInfoList.Sort(),但它没有生效。

4个回答

26

使用sort方法和lambda表达式非常简单。

myList.Sort((a, b) => String.Compare(a.Name, b.Name))

以上示例展示了如何按照对象类型的“Name”属性进行排序,假设“Name”是字符串类型。


你可以使用string.Compare(a.Name, b.Name),这样会安全一些吗? - Marc Gravell
谢谢!每天都学点新东西...我会编辑答案。 - m-sharp

8
如果你只想让Sort()起作用,那么你需要在类中实现IComparableIComparable<T>
如果你不介意创建一个新列表,你可以使用OrderBy/ToList LINQ扩展方法。如果你想用更简单的语法对现有列表进行排序,你可以添加一些扩展方法,使其支持:
list.Sort(item => item.Name);

例如:

public static void Sort<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(x), selector(y)));
}
public  static void SortDescending<TSource, TValue>(
    this List<TSource> source,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    source.Sort((x, y) => comparer.Compare(selector(y), selector(x)));
}

你有使用这些扩展方法的示例吗?我尝试使用它来回答我的问题http://stackoverflow.com/questions/31057258/sort-list-of-dictionary-using-icomparer-instead-of-orderby,但是无法按照你建议的方式实现。 - Mrinal Kamboj

2
public class Person  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

List<Person> people = new List<Person>();

people.Sort(
    delegate(Person x, Person y) {
        if (x == null) {
            if (y == null) { return 0; }
            return -1;
        }
        if (y == null) { return 0; }
        return x.FirstName.CompareTo(y.FirstName);
    }
);

1

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