0

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
     }
StarLight
  • 59
  • 7
  • Just implement the interface IComparable on your class C. Nothing too fancy or complicated. You can let the intellisense do all the work and write down the logic about how to do the actual comparison in the CompareTo method. – Bizhan Dec 16 '21 at 23:32
  • Welcome to Stack Overflow. "I need to use a IComparable comparsion interface, but I don't understand how it works." Well, did you read the documentation for `IComparable`? Did you try putting `c# sorting tutorial` or `c# icomparable tutorial` into a search engine? Please read https://meta.stackoverflow.com/questions/261592. – Karl Knechtel Dec 16 '21 at 23:32
  • 1
    Fundamentally, the question you have to answer is: "Given two `C`s, what is the rule that says which one is 'smaller'?" The language will not guess your intent here. You must write code that implements that rule. You use the interface in order to *signal* that your code is implementing that rule. – Karl Knechtel Dec 16 '21 at 23:34

1 Answers1

3

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);  
  }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215