tags:

views:

80

answers:

3

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?

+1  A: 

You have to implement IComparable in the class first. These should help:
Sort ArrayList Of Objects
How to use the IComparable and IComparer interfaces in Visual C#

o.k.w
+5  A: 

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));
Jon Skeet
A: 
class Program
{
    class Foo
    {
        public int FirstMemberValue { get; set; }
    }

    static void Main(string[] args)
    {
        var foos = new[] 
        { 
            new Foo { FirstMemberValue = 1 }, 
            new Foo { FirstMemberValue = 3 }, 
            new Foo { FirstMemberValue = 2 } 
        };
        Array.Sort(foos, (f1, f2) => f1.FirstMemberValue.CompareTo(f2.FirstMemberValue));
        foreach (var item in foos)
        {
            Console.WriteLine(item.FirstMemberValue);
        }
    }
}
Darin Dimitrov