Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of objects (classes)?

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
     }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);  
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading