List Conversion

9 Jan

One of my favourite use cases for lambda expressions in .NET is converting lists. Take the following code as an example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

 

namespace LambdaComparison

{

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

 

            IList<Person> people = new List<Person>();

 

            Example1(people);

            Example2(people);

        }

 

        public void Example1(IList<Person> people)

        {

            var names = people

                          .Select(item => item.Name).ToList();

        }

 

        public void Example2(IList<Person> people)

        {

            var names = new List<String>();

 

            foreach (var person in people)

            {

                names.Add(person.Name);

            }

        }

    }

 

    public class Person

    {

        public String Name

        {

            get; set;

        }

    }

}

From using this approach for converting lists between types I have found that it leads to more readable code, as it is one line rather than many.

One other thing that is worth noting and is very important tip when using LINQ or lambda expressions, is that the return type is IEnumerable<T>. Often when using LINQ etc it is common for people to expect a list or use the "var" keyword. The var keyword is not actually a type but rather is implicitly typed which means that the compiler infers/computes the type based on the right hand side of an assignment. I usually use var but i had issues with more complex LINQ statements until I realised how to understand what the var keyword was representing and how it was being deduced (which is not immediately obvious for beginners with many LINQ statements). LINQ also offers the ability to create annonymous types which provide challenges in the area of non implicit typing.

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

%d bloggers like this: