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?
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?
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#
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:
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:
Array.Sort(array, (x1, x2) => x1.MemberName.CompareTo(x2.MemberName));
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);
}
}
}