I’m trying to sort an array of objects with Array.Sort, but get an InvalidOperationException. As i have read i’m trying to sort a complex object and I need to use a IComparable <T> comparsion interface, but I don’t understand how it works.
There is my code:
public class C
{
public int I { get; set; }
}
static void Main(string[] args)
{
C[] classes = new C[100000];
Random rand = new Random();
for (int i = 0; i < 100000; i++)
{
classes[i] = new C { I = rand.Next(1, 100000) };
}
Array.Sort<C>(classes); // Here I get an exception
}
>Solution :
You should explain to .Net how to compare classes:
...
// having a and b instances we should compare I properties
Array.Sort<C>(classes, (a, b) => a.I.CompareTo(b.I));
...
Or you can make class C comparable (in order Array.Sort<C>(classes); to start working):
public class C : IComparable<C> {
public int I { get; set; }
public int CompareTo(C other) {
if (null == other)
return 1;
return I.CompareTo(other.I);
}
}