如果你只是想Sort()
工作,那么你需要实现IComparable
或IComparable<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)));
}