Monday, July 29, 2019

Sort with an IComparer in C#!

using System.Collections.Generic;
namespace Trifecta.Core.Objects
{
   public class NumberSorter : IComparer<int>
   {
      public int Compare(int x, int y)
      {
         return x.CompareTo(y);
      }
   }
}

 
 

Use your implementation like this:

List<int> foo = new List<int>() { 42, 13, 86, 69 };
NumberSorter numberSorter = new NumberSorter();
foo.Sort(numberSorter);
List<int> bar = foo;

 
 

It does what you think it does. It puts the numbers in order. Note that when you do this with a string, there is still an int being returned at the IComparer implemenation not a string. That part is not customized to the generic. It is always an int.

using System.Collections.Generic;
namespace Trifecta.Core.Objects
{
   public class StringSorter : IComparer<string>
   {
      public int Compare(string x, string y)
      {
         return x.CompareTo(y);
      }
   }
}

No comments:

Post a Comment