25

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.

Community
  • 1
  • 1
Mr. Smith
  • 5,489
  • 11
  • 44
  • 60
  • 4
    Exact dup of http://stackoverflow.com/questions/1301822 – Jon Skeet Aug 20 '09 at 06:26
  • 1
    It's not the same thing as far as I'm concerned. – Mr. Smith Aug 20 '09 at 06:30
  • **Well, *by all appearances,* it's the same thing.** If you're gonna contest a duplicate flag, then at least be prepared to explain why your question is different from one previously asked, and why the answers given for that one won't help you in your situation. Otherwise, what's the point? – Shog9 Aug 21 '09 at 18:26
  • Not enough blood in your nicotine stream, eh Shog? :) – Mr. Smith Aug 21 '09 at 21:45
  • Something like that. :-) – Shog9 Aug 21 '09 at 22:00
  • 4
    This doesn't appear to be a duplicate to me, despite the fact the titles are similar, because the other question is actually about Lists, not arrays. The accepted answer is using Linq and List functionality that arrays lack. The accepted answer here is what worked for me, while those answers couldn't. – Joe M Mar 02 '16 at 16:55

2 Answers2

39

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); });
LukeH
  • 263,068
  • 57
  • 365
  • 409
22

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();
Simon Fox
  • 10,409
  • 7
  • 60
  • 81