The diary of a .NET Developer, working on an unlaunched startup project. Also, I live and work in Southern Oregon.

Tuesday, February 10, 2009

Comparison<T> and IComparable<T> vs LINQ

Sorting Before LINQ:

  • Implement IComparable<T> so you can use the default sort.
  • Add a few Comparision<T> delegates so I could sort other ways
public class DrawDown : IComparable<T> : IComparable<T>
{
public static Comparison<DrawDown> DateComparison = delegate(DrawDown field1, DrawDown field2) { }
public static Comparison<DrawDown> ValueComparison = delegate(DrawDown field1, DrawDown field2) { }
public int CompareTo(DrawDown other) {}
}

And sort like this:

var list = new List<DrawDown>();
list.Sort();
//or
list.Sort(DrawDown.DateComparison);

Sorting with LINQ:

var list = new List<DrawDown>();
list.OrderBy(d=>d.Date);
//or
list.OrderBy(d=>d.Value);

Basically, I use LINQ more then anything else in the .NET framework.  It really does save hours of writing boring “sort” code.


NOTE: I am working on getting better syntax highlighting in my blog.  Live Writer  is not working out at all.

No comments:

Post a Comment