Tuesday, May 6, 2008

In this blog article I would like a take a simple code example in C# and explore the different ways of expressing it using LINQ, Anonymous methods and Lambda Expressions.

Code Sample:
Let's start by defining a simple class Person

public class Person
{
public Person(string name, int age)
{
if(!string.IsNullOrEmpty(name) & age > 0)
{
Name = name;
Age = age;
}
}

public string Name { get; set; }
public int Age { get; set; }
}

As first step let's create a List<Person> and initialize with some people as follows:

static void Main(string[] args)
{
PopulateSample();
}

private static void PopulateSample()
{
persons = new List<Person>();

persons.Add(new Person("Joe", 40));
persons.Add(new Person("Steve", 35));
persons.Add(new Person("Mike", 29));
persons.Add(new Person("Dan", 45));
persons.Add(new Person("Jeff", 30));
}

Now that we have some data to work with as a next step let's try to find all the people in the list whose age is above 31 and print their names. As soon as try to write a solution to this, the first thing that comes to my mind is iterating through the list using a foreach loop. A very basic code sample would be as follows:


private static void ExecuteSampleUsingForEach()
{
Console.WriteLine("The Result using Foreach method:");
foreach(Person p in persons)
{
if(p.Age > 31)
{
Console.WriteLine(p.Name);
}
}

}

There is absolutely nothing wrong with this approach. But there are different methods of representing the same thing in code. The following methods may look very different but they all yield the same result.

private static void ExecuteSampleUsingAnonymousMethod()
{
IEnumerable<Person> peopleWithLongNames = persons.FindAll(delegate(Person p){return p.Age > 31; });
Console.WriteLine("The Result using Anonymous Method:");
foreach(Person person in peopleWithLongNames)
{
Console.WriteLine(person.Name);
}
}

private static void ExecuteSampleUsingLINQ()
{
IEnumerable<Person> peopleWithLongNames = from p in persons where p.Age > 31 select p;
Console.WriteLine("The Result using LINQ:");
foreach(Person person in peopleWithLongNames)
{
Console.WriteLine(person.Name);
}
}

private static void ExecuteSampleUsingLambdaExpressions()
{
IEnumerable<Person> peopleWithLongNames = persons.Where(p => p.Age > 31);
Console.WriteLine("The Result using Lambda Expressions:");
foreach(Person person in peopleWithLongNames)
{
Console.WriteLine(person.Name);
}
}

As a developer one of my goals is to write less but elegant code. With Framework 3.5 C# gives so many options to do the same thing. As developers it's up to us to use the right way at the right place.

5 comments:

Anonymous said...

Architecturally, I feel, above all, it pays to be consistent in your code. The Lambda expression is more pleasing, certainly. Very OO, easy to read, consise, pure. However, it breaks down when you want to do a "join" over two objects. So, my answer, then ... it depends. Here are the questions I would ask in order to make a decision: (1) If your domain is pretty "simple", use the more elegant. (2) If your domain is complex, be more flexible for joins (3) If your codebase is really large and complex (and you come from a marketing background) do both options - but make sure you have standards for each.

Anonymous said...

Online Pharmacy for Cialis, Levitra, Tamiflu, Viagra. Order Generic Medication In own Pharmacy. Buy Pills Central.
[url=http://buypillscentral.com/news_en-us.htm]Discount Viagra, Cialis, Levitra, Tamiflu Drugstore No prescription[/url]. canadian generic drugs. Discount drugs pharmacy

windows 7 said...

Absolutely brilliant post guys, been following your blog for 3 days now and i should say i am starting to like your post. and now how do i subscribe to your blog?

Ed Levitra said...

My name is Ed Levitra from Toronto. I am interested in your writing. Some of your posting are good, I can say, best. Can you please tell me how to subscribe to your blog post online?

Anil Sharma said...

I think you have a great page here… today was my first time coming here.. I just happened to find it doing a google search. anyway, good post.. I’ll be bookmarking this page for sure.


Web hosting