C# 如何根据 T 的属性对 List<T> 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/605189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort List<T> based on properties of T?
提问by
My Code looks like this :
我的代码如下所示:
Collection<NameValueCollection> optionInfoCollection = ....
List<NameValueCollection> optionInfoList = new List<NameValueCollection>();
optionInfoList = optionInfoCollection.ToList();
if(_isAlphabeticalSoting)
Sort optionInfoList
I tried optionInfoList.Sort() but it is not working.
我试过 optionInfoList.Sort() 但它不起作用。
回答by mezoid
You need to set up a comparer that tells Sort() how to arrange the items.
您需要设置一个比较器来告诉 Sort() 如何排列项目。
Check out List.Sort Method (IComparer)for an example of how to do this...
查看List.Sort Method (IComparer)以获取如何执行此操作的示例...
回答by m-sharp
Using the sort method and lambda expressions, it is really easy.
使用 sort 方法和 lambda 表达式,真的很容易。
myList.Sort((a, b) => String.Compare(a.Name, b.Name))
The above example shows how to sort by the Name property of your object type, assuming Name is of type string.
上面的示例显示了如何按对象类型的 Name 属性排序,假设 Name 是 string 类型。
回答by Marc Gravell
If you just want Sort()
to work, then you'll need to implement IComparable
or IComparable<T>
in the class.
如果你只是想Sort()
工作,那么你就需要实现IComparable
或IComparable<T>
在课堂上。
If you don't mind creating a newlist, you can use the OrderBy
/ToList
LINQ extension methods. If you want to sort the existing list with simpler syntax, you can add a few extension methods, enabling:
如果您不介意创建一个新列表,则可以使用OrderBy
/ ToList
LINQ 扩展方法。如果要使用更简单的语法对现有列表进行排序,可以添加一些扩展方法,启用:
list.Sort(item => item.Name);
For example:
例如:
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)));
}
回答by Nick Kahn
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);
}
);