C# – How to sort an array of objects in Visual C#

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:

array = array.OrderBy(x => x.MemberName).ToArray();

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:

  • Make your type implement IComparable<T> allowing an object to compare itself with another
  • Create an instance of IComparer<T> which can compare any two objects of that type
  • Create a delegate of type Comparison<T> which can compare any two objects of that type

The last is probably the easiest solution if you're using C# 3:

Array.Sort(array, (x1, x2) => x1.MemberName.CompareTo(x2.MemberName));