System.Collections.Generic.IComparer

Provides additional comparison mechanisms
This allows you to provide ordering of your class on several fields or properties, ascending or descending order on the same field or both.


Which Interface

IComparable - Provides a comparer check (for sorting) when there is only on way ot ordering the objects (implemented inside the class)
IComparer - Allows you to define and use multiple comparer checks (implemented outside the class)


When you implement the IComparer there are two steps.


First declare a class that implements IComparer

private class SortAscendingHelper : IComparer 
{
   int IComparer.Compare(object a, object b)
   {
      myobject = my1 (myObject)a;
      myobject = my2 (myObject)b;
      if (my1.MySortProperty > my2.MySortProperty)
      {
         return 1;
      }
      if (my1.MySortProperty < my2.MySortProperty)
      {
         return -1;
      }
      return 0;
   }
}

Second implement the Compare method.

public static IComparer sortAscending() 
{
   return (IComparer) new SortAsecendingHelper();
}


© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext