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.
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.
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.
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.
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.
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); });
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With