How to sort an array containing class objects by a property value of a class instance? [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

Possible Duplicate:
How to sort an array of object by a specific field in 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:

myClassArray[0].Name //'James'; myClassArray[1].Name //'Jess'; myClassArray[2].Name //'John'; 

*Edit: I'm using VS 2005/.NET 2.0.

回答1:

You can use the Array.Sort overload that takes a Comparison<T> parameter:

Array.Sort(myClassArray,     delegate(MyClass x, MyClass y) { return x.Name.CompareTo(y.Name); }); 


回答2:

Have MyClass implement IComparable interface and then use Array.Sort

Something like this will work for CompareTo (assuming the Name property has type string)

public int CompareTo(MyClass other) {     return this.Name.CompareTo(other.Name); } 

Or simply using Linq

MyClass[] sorted = myClassArray.OrderBy(c => c.Name).ToArray(); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!