27

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.

6
  • 4
    Exact dup of stackoverflow.com/questions/1301822 Commented Aug 20, 2009 at 6:26
  • 1
    It's not the same thing as far as I'm concerned. Commented Aug 20, 2009 at 6: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? Commented Aug 21, 2009 at 18:26
  • Not enough blood in your nicotine stream, eh Shog? :) Commented Aug 21, 2009 at 21:45
  • 5
    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. Commented Mar 2, 2016 at 16:55

2 Answers 2

43

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); });
Sign up to request clarification or add additional context in comments.

1 Comment

I needed the same but with descending order, just negated the return result. it worked fine :)
27

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.