I have an object that has two members that are both integer values. I made an array of these objects. Each objects values are filled with random integers.
I want to sort the array of objects according to the first member value. How would I do this?
arrayscobject
I have an object that has two members that are both integer values. I made an array of these objects. Each objects values are filled with random integers.
I want to sort the array of objects according to the first member value. How would I do this?
Best Answer
Are you using .NET 3.5? If so, it's as easy as:
That will create a new array though - if any other code has a reference to the old array, it will still see the unsorted data.
Alternatively, you can use the
Array.Sort
method which will sort the array in-place, in one of three ways:IComparable<T>
allowing an object to compare itself with anotherIComparer<T>
which can compare any two objects of that typeComparison<T>
which can compare any two objects of that typeThe last is probably the easiest solution if you're using C# 3: