Lambda Expressions Demonstration

I’ve been learning some of the new C# language features in the 3.5 framework. One of them is lambda expressions.

I’ve been a big fan of using delegates to search through lists, etc… and lambda is going to help shorten the code to do this. Below is a simple example showing the ‘new’ and the ‘old’ way:

        [Test]
        public void UsingLambdaTest()
        {
            List<Person> people = new List<Person>();
            people.Add(new Person("Steve"));
            people.Add(new Person("Jake"));
            people.Add(new Person("Tyler"));
            people.Add(new Person("Evan"));
            people.Add(new Person("Gina"));

            //with lambda - new:
            var namesWithanN = people.FindAll(name =>
                               name.FirstName.ToUpper().Contains("N"));

            Assert.That(namesWithanN.Count, Is.EqualTo(2));

            //with delegate - old:
            List<Person> peopleWithLetterN = people.FindAll(delegate(Person name)
                                                                {
                                                                    return (name.FirstName.ToUpper().Contains("N"));
                                                                });

            Assert.That(peopleWithLetterN.Count, Is.EqualTo(2));
        }

The use of the var is still typed, and the use of ‘name’ above has intellisense in Visual Studio 2008.

A cool feature here is the available options with var.

ie. take that subset and get a list of those returned:

List<Person> peopleWithN = namesWithanN.ToList<Person>();

More to come… Merry Christmas everyone!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s