Thursday, May 7, 2009

C# Puzzle No.15 (intermediate)

We have two types of "comparers" in C#: the IComparer (IComparer<T>) interface and Comparison<T>.

In deep past, before generics were introduced, the base class library used IComparer everywhere. For example, the ArrayList class can sort items using custom IComparer passed as a parameter to the Sort() method.

When generics were introduced, the base class library in many cases allows either an IComparer or Comparison to be passed to sorting methods. For example, the List<T>'s Sort method accepts either the former or the latter.

It's fairly easy to convert from IComparer to Comparison<T>. Take a look at this example:

   1: class Program
   2:  {
   3:      class IntSorter : IComparer
   4:      {
   5:          #region IComparer Members
   6:  
   7:          public int Compare( object x, object y )
   8:          {
   9:              return ( (int)x ).CompareTo( (int)y );
  10:          }
  11:  
  12:          #endregion
  13:      }
  14:  
  15:      static void Main( string[] args )
  16:      {
  17:          List<int> l = new List<int>() { 4,3,2,5,3,2,1 };
  18:         
  19:          /* 
  20:             convert the an IComparer to Comparison<int>
  21: 
  22:             (x,y) => ( new IntSorter() ).Compare( x, y ) 
  23: 
  24:             is the answer
  25:           */
  26:          l.Sort( ( x, y ) => ( new IntSorter() ).Compare( x, y ) );
  27:  
  28:          /* test */
  29:          l.ForEach( i => Console.Write( i ) );
  30:  
  31:          Console.ReadLine();
  32:      }
  33:  }

However, what should we do to convert the other way around?


Specifically, take a look at this code snippet



   1: class Program
   2:  {
   3:      /* this is the Comparison<int> to be converted */
   4:      static int IntComparer( int x, int y )
   5:      {
   6:          return x.CompareTo( y );
   7:      }
   8:  
   9:      static void Main( string[] args )
  10:      {
  11:          ArrayList a = new ArrayList() { 1, 5, 3, 3, 2, 4, 3 };
  12:  
  13:          /* the ArrayList's Sort method accepts ONLY an IComparer */
  14:          a.Sort( how to pass the IntComparer here ? );
  15:  
  16:          Console.ReadLine();
  17:      }
  18:  }
and find an ellegant way to pass the Comparison<int> as IComparer to ArrayList's Sort method.

No comments: