Fun with Generics – Simple sorting, pre-Linq

I recently attended the IowaCodeCamp.  I’ve found that going to these kinds of things always gets my brain buzzing with all kinds of things I want to try out.  In one talk I attended the presenter made the comment that most people have very little experience with Generics outside of using Generic Collections.  From what I’m seeing out there on the web, I would have to agree.  I’ve been playing a lot with Generic functions and classes recently and wanted to post a fun example I’ve come up with.  If this is useful to you, please feel free to grab it and reuse it.
So I wrote this because I love how easy Linq makes some things, like sorting (Ordering).  However, where I’m working, we’re not on the 3.5 Framework yet, so I can’t take advantage of the cool OrderBy function with Lambdas.  However, being able to order a collection quickly is a super nice feature.  So I wrote this function.  Hope you like it.
private Comparison GetComparison(String fieldName)
{
	List properties = new List(typeof(T).GetProperties());

	PropertyInfo property = properties.Find(

	  delegate(PropertyInfo propertyInfo)
	  {
		  return propertyInfo.Name.Equals(fieldName);
	  }

	);

	if (property != null)
	{
		return delegate(T obj1, T obj2)
		{
			IComparable value1 = (IComparable)property.GetValue(obj1, null);
			IComparable value2 = (IComparable)property.GetValue(obj2, null);
			return value1.CompareTo(value2);
		};
	}

	throw new ArgumentException(String.Format("Object {0} has no property called {1}",
		typeof(T).Name, fieldName));
}

This function can then be invoked like this:

private List GetSortedList()
{
    List people = new List
    {
        new Person{ FirstName = "Jim", LastName = "Smith", Address = "100 C Street" },
        new Person{ FirstName = "Amy", LastName = "Jones", Address = "100 A Street" },
        new Person{ FirstName = "Larry", LastName = "Johnson", Address = "100 B Street"}
    }; 

    people.Sort(GetComparison("Address"));
}

I still prefer using Linq, but when I can’t, this is a nice little helper function.  Using similar techniques, your own 2.0 replacements for nice Linq functions can be created pretty easily.

Enjoy!

Getting to Lambda

An exploration of Lambda expressions for newer .NET developers.

I’ve seen quite a few articles about Lambda expressions geared toward experienced developers, but I haven’t really seen a lot that try to bridge the gaps for us “regular folks”.  Hopefully this series of blog posts will approach this topic in an easy to understand manner.

What are Lambda expressions?

Lambda expressions are a neat shorthand way of passing functionality between functions and are the logical next step from delegates.  If that doesn’t mean much to you, that’s ok.  During this series of posts, I hope to show by example that Lambda expressions are both powerful and really pretty easy to use.

The Evolution of the Lambda expression.

I know that Lambda expressions can be pretty scary and confusing the first time you see them.  I know I stared at several before I really started to understand what was going on with them.  So let’s take a step back to some familiar territory and build up to Lambda expressions from there.

Let’s say that we have a collection of strings that we want to turn to upper case.  We’ve probably all written code like this…

ArrayList stringList = new ArrayList();
stringList.Add("hello");
stringList.Add("goodbye");

ArrayList capitalizedList = new ArrayList();

foreach (String item in stringList)
{
    capitalizedList.Add(item.ToUpper());
}

The foreach command structure is something that we’re all probably pretty familiar with.  The one drawback it has is the cast that’s happening as each item is assigned from the ArrayList.  What happens if something other than a string gets added to the ArrayList?  Pure pandemonium!  Well, an exception at any rate.  Fortunately for us, .NET 2.0 introduced us to the concept of Generics (a great topic for another blog post) and more importantly for this discussion, the Generic List.  The Generic List class includes a ForEach() method that works very much like the foreach command structure but because we’re using a strongly typed Generic, we don’t have the cast to worry about.  Let’s take a look at the example from above rewritten to use the Generic List class’s ForEach() method.

List<String> stringList = new List<string>();
stringList.Add("hello");
stringList.Add("goodbye");

List<String> capitalizedList = new List<string>();
stringList.ForEach(
    delegate(String item)
    {
        capitalizedList.Add(item.ToUpper());
    }
);

So if we look closely, this really doesn’t look too different from the example using the foreach command structure.  The biggest difference is that our collection is strongly typed now because of the Generic List so we don’t have to worry about the overhead of the cast or the possibility of some type other than string sneaking into the list.  That is checked at compile time now.  If the delegate statement looks strange to you, don’t worry.  I’ll be covering that in an upcoming post.  The key is that we’re passing functionality into the ForEach() method in the form of an anonymous method.  In this case, it’s a method that takes a string as a parameter (the item parameter).

Lambda expressions are simply a shorthand way of writing these types of anonymous methods.  They use the Lambda Operator “=>” which is often read as “goes into”.  So let’s look at the exact same method from above, but we’ll use the Lambda expression shorthand.

List<String> stringList = new List<string>();
stringList.Add("hello");
stringList.Add("goodbye");

List<String> capitalizedList = new List<string>();
stringList.ForEach( item => capitalizedList.Add(item.ToUpper()) );

In this example, I’m purposely using the same names I did in the example I did above so it’s apparent how the pieces fit together.  The lambda expression can be read as “the parameter item goes into the function where…”.  As you can see, the exact same thing is happening here that was happening in the more verbose delegate version, but the code is much more compact.  Once you get used to the syntax, I think you’ll even agree that the code is much easier to read with the Lambda expression.

Ok, so admittedly, this was a very contrived example, but it was meant as an introduction.  Stay tuned and we’ll move into some more realistic examples of where and how Lambda expressions can be used.