C# 如何通过类实例的属性值对包含类对象的数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1304278/
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 to sort an array containing class objects by a property value of a class instance?
提问by Mr. Smith
Possible Duplicate:
How to sort an array of object by a specific field in C#?
可能的重复:
如何按 C# 中的特定字段对对象数组进行排序?
Given the following code:
鉴于以下代码:
MyClass myClass;
MyClassArray[] myClassArray = new MyClassArray[10];
for(int i; i < 10; i++;)
{
myClassArray[i] = new myClass();
myClassArray[i].Name = GenerateRandomName();
}
The end result could for example look like this:
例如,最终结果可能如下所示:
myClassArray[0].Name //'John';
myClassArray[1].Name //'Jess';
myClassArray[2].Name //'James';
How would you sort the MyClassArray[] array according to the myClass.Name property alphabetically so the array will look like this in the end:
您将如何根据 myClass.Name 属性按字母顺序对 MyClassArray[] 数组进行排序,以便数组最终看起来像这样:
myClassArray[0].Name //'James';
myClassArray[1].Name //'Jess';
myClassArray[2].Name //'John';
*Edit: I'm using VS 2005/.NET 2.0.
*编辑:我使用的是 VS 2005/.NET 2.0。
采纳答案by LukeH
You can use the Array.Sort
overload that takes a Comparison<T>
parameter:
您可以使用Array.Sort
带Comparison<T>
参数的重载:
Array.Sort(myClassArray,
delegate(MyClass x, MyClass y) { return x.Name.CompareTo(y.Name); });
回答by Simon Fox
Have MyClass implement IComparableinterface and then use Array.Sort
让 MyClass 实现IComparable接口,然后使用Array.Sort
Something like this will work for CompareTo (assuming the Name property has type string)
像这样的东西将适用于 CompareTo(假设 Name 属性具有类型字符串)
public int CompareTo(MyClass other)
{
return this.Name.CompareTo(other.Name);
}
Or simply using Linq
或者干脆使用 Linq
MyClass[] sorted = myClassArray.OrderBy(c => c.Name).ToArray();