使用LINQ对类列表进行排序

Kub*_*ubi 3 linq

我有一个List<MyClass>,我想按DateTime CreateDateMyClass 的属性对其进行排序.

这可能与LINQ有关吗?

谢谢

Mar*_*ell 5

要对现有列表进行排序:

list.Sort((x,y) => x.CreateDate.CompareTo(y.CreateDate));
Run Code Online (Sandbox Code Playgroud)

也可以编写Sort扩展方法,允许:

list.Sort(x => x.CreateDate);
Run Code Online (Sandbox Code Playgroud)

例如:

public static class ListExt {
    public static void Sort<TSource, TValue>(
            this List<TSource> list,
            Func<TSource, TValue> selector) {
        if (list == null) throw new ArgumentNullException("list");
        if (selector == null) throw new ArgumentNullException("selector");
        var comparer = Comparer<TValue>.Default;
        list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
    }
}
Run Code Online (Sandbox Code Playgroud)