C# Generic Lambda Comparer

public class LambdaComparer<T> : IComparer<T>
{
  public enum Direction
  {
    Asc = 1,
    Desc = -1
  }
 
  private readonly Comparison<T> _comparison;
 
  public LambdaComparer(Comparison<T> comparison)
  {
    _comparison = comparison;
  }
 
  int IComparer<T>.Compare(T x, T y)
  {
    return _comparison(x, y);
  }
 
  public static LambdaComparer<T> IgnoreSortComparer()
  {
    return IgnoreSortComparer(Direction.Asc);
  }
 
  public static LambdaComparer<T> IgnoreSortComparer(Direction direction)
  {
    return new LambdaComparer<T>((x, y) => x.Equals(y) ? 0 : (int)direction);
  }
}
public class Data
{
  public int X;
  public int Y;
}
 
[Test]
public void TestLambdaComparer()
{
  var data = new Data[]
  {
  new Data() { X = 1, Y = 1 }, 
  new Data() { X = 3, Y = 2 }, 
  new Data() { X = 5, Y = 3 }, 
  new Data() { X = 2, Y = 4 }, 
  new Data() { X = 4, Y = 5 }   
  };
 
  Console.WriteLine("BEFORE: "+string.Join(",",data.Select(x=>string.Format("{0}={1}",x.X,x.Y))));
 
  Array.Sort(data, new LambdaComparer<Data>((a,b)=>a.X.CompareTo(b.X)));
 
  Console.WriteLine("AFTER : " + string.Join(",", data.Select(x => string.Format("{0}={1}", x.X, x.Y))));   
 
  //BEFORE: 1=1,3=2,5=3,2=4,4=5
  //AFTER : 1=1,2=4,3=2,4=5,5=3
}
[Test]
public void TestIgnoreSortComparer()
{
  var defaultSortedSet = new SortedSet<int>();
  defaultSortedSet.Add(2);
  defaultSortedSet.Add(3);
  defaultSortedSet.Add(1);
 
  Console.WriteLine("DEFAULT  : " + string.Join(",", defaultSortedSet));
 
  var unSortedSet = new SortedSet<int>(LambdaComparer<int>.IgnoreSortComparer());
  unSortedSet.Add(2);
  unSortedSet.Add(3);
  unSortedSet.Add(1);
 
  Console.WriteLine("UNSORTED : " + string.Join(",", unSortedSet));
 
  var unSortedList = new SortedList<int,int>(
    LambdaComparer<int>.IgnoreSortComparer(LambdaComparer<int>.Direction.Desc));
  unSortedList.Add(2,1);
  unSortedList.Add(3,2);
  unSortedList.Add(1,3);
 
  Console.WriteLine("UNSORTED : " + string.Join(",", unSortedList));
 
  //DEFAULT  : 1,2,3
  //UNSORTED : 2,3,1
  //UNSORTED : [2, 1],[3, 2],[1, 3]
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#