views:

152

answers:

4

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.

A: 

Implement ICompare interface and use Array.Sort() method.

adatapost
+3  A: 

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
A: 

Why arrays? Cant you use a List, which has builtin sorting capabilities? (And can also be dynamically sized, items added/removed, etc.)

Simon Svensson
I'm calling a web service method which expects an object of MyClassArray[], containing the myClass object also defined by the same web service. myClass has 137 properties. The web service takes MyClassArray[] and loops through it to use the property values for each instance of myClass as field values to populate a table in a database.
Mr. Smith
List has a ToArray method...
Paolo Tedesco
@Simon: Why would `List<T>.Sort` be any better or easier than `Array.Sort` in this situation?
LukeH
@Luke, he can change his service proxy to expose arrays as lists (or collections), they are nicer to expose, they can be expanded/shrinked. They are usually better than a hardcoded array.
Simon Svensson
+1  A: 

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
Perfect, thanks Luke.
Mr. Smith