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

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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.

Wednesday, February 4, 2009

Char to Int vs String to Int

I spent way to much time staring at this code trying to figure this out:

int number = 10;
int firstDigit = Convert.ToInt32(number.ToString()[0]);
Assert.AreEqual(1,firstDigit) //fails: firstDigit == 49

I knew it was returning the Unicode value of 1, which is 49, but I was after the integer value.  Converting a char to an int always returns the Unicode value, not the integer value.  Converting a string returns the expected result.

int number = 10;
int firstDigit = Convert.ToInt32(number.ToString()[0].ToString()); //add an extra ToString()
Assert.AreEqual(1,firstDigit) //passes

Nothing too exciting, but I was stumped for about 15 minutes trying to figure this out.  I almost started looking for a atoi() function.