Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 247
Mr. Smith Avatar asked Aug 20 '09 06:08

Mr. Smith


People also ask

How do you sort an array of objects based on a property?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

How do you sort an array of objects by property value in Swift?

To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.

How do you filter an array of objects in JavaScript based on property value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you sort a class array?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.


2 Answers

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); });
like image 76
LukeH Avatar answered Oct 13 '22 15:10

LukeH


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();
like image 28
Simon Fox Avatar answered Oct 13 '22 16:10

Simon Fox