Lambda Expressions – Easier to Read, Easier to Maintain

lambdaImage Source

It is always good to write LESS code the shorter the better, nobody wants their code equivalent to an epic. Writing less code means you are writing less bugs.

Most of the common problems are already solved it is good practice to use Libraries. Libraries are constantly improved and they are tested my millions of people.

Lambda Expressions

Lambda expressions were introduced in C # 3 (. NET 3.5). These expressions are now used everywhere in the code, to make LINQ queries to filter on lists for delegates and events.

Lambda expression can be confusing if you are new to it , but once you understand what lambda expression is , which is simply and anonymous function which we can use in our advantage to create our very compact and elegant code .

Anatomy of lambda expression is very simple.

All expressions use the lambda operator => (reads “leads to”).
On the left hand side we have the parameters these can be zero one or more parameters  next we have the equal greater than sign =>  this is the lambda operator also known as the goes to operator and then on the right hand side we either have an expression or series of statements that perform some type of work  .

The first thing you will notice in lambda expressions is the use of single letter parameter names this makes things much more compact.

Lets see here in an expression lambda.
(pet p) => p.Name==”Kitty Gaga”

Now we just have pet p and p.Name, remember this is just a convention this is not required. You can name your parameters whatever you want , however due to the compact nature of lambda expression people always assign single letter parameter names .

Addition to these conventions there is also some syntactic variations.

Optional parameter types:

(s, e) =>{MyListBox.ItemsSource=e.Result;}

The parameter types are often optional if the compiler can figure out the types of parameter than we don’t need to specify them.

So in this case this case we have object s and event args e but we don’t actually need to specify the object or event types because the compiler knows that already.

Optional parentheses for single parameter:

e =>{MyListBox.ItemsSource=e.Result;}

If we only have single parameter we don’t need parentheses around them this is something that is very common especially in LINQ.


Optional Braces for single statement:

e =>MyListBox.ItemsSource=e.Result;

If we have statement lambda with just one statement the curly braces are optional.


Empty parentheses or no parameter:

()=>{ Console.WriteLine(“Kitty Gaga”);}

There are times when lambda expression doesn’t have any parameter at all in those cases they are just a set of empty parentheses rather than parameters.

Now let’s see lambda expression in action with an example, just look at the code and think yourself why LINQ is the way to do it.

      pet[] pets = { new pet{ Name = "Kami Kazi", age = 10}, 
                     new pet{ Name = "Spark Pug", age = 10},
                     new pet{ Name = "Kami Kazi", age = 10},
                     new pet{ Name = "Kitty Gaga", age = 10},
                     new pet{ Name = "Kitty Gaga", age = 3},
                     new pet{ Name = "Kitty Gaga", age = 2}};

      pet[] pets2 ={ new pet{ Name = "Kami Kazi", age = 11 }, 
                     new pet{ Name = "Spark Pug", age = 12 },
                     new pet{ Name = "Kami Kazi", age = 15 },
                     new pet{ Name = "Kitty Gaga", age = 10},
                     new pet{ Name = "Kitty Gaga", age = 3 },
                     new pet{ Name = "Kitty Gaga", age = 2 }};

we have two collection of Pets and we need to get different kind of result by comparing and manipulating them.

 This query will select and return just the names of pets.
 var petNames = pets.Select(p => p.Name).ToList();

 This will return pets ordered by their names.
 var simpleOrderdPets = pets.OrderBy(p => p.Name).ToList();

 Now let’s get pets with multiple order by, remember not to use OrderBy again
 the second ordering is done by ThenBy.
 var orderdpetsWithMultipleOrderby = pets.OrderBy(p => p.Name).ThenBy(p => p.age).ToList();

 Now let’s use OrderByDescending here also we need to use ThenByDescending
 if we want to apply multiple order condition.
 var orderdPetsDescending = pets.OrderByDescending(p => p.Name).ThenByDescending(p => p.age).ToList();

 We can also create our custom compare class and pass it to the linq query.
 var orderdpetsCustomComparer = pets.OrderBy(p => p.Name, new CaseInsensitiveComparer()).ToList();
    public class CaseInsensitiveComparer : IComparer<string>
       public int Compare(string x, string y)
        return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);

Now it’s Time to Show Off  try writing the Code below in native C# and any other language to get these task done.

Find Duplicate pets. 
var duplicates = pets.GroupBy(i => new { i.Name }).Where(g => g.Count() > 1).Select(g => g.Key);

Find distinct Pets remember we are applying distict on both name and age.
var distinctPets = pets.GroupBy(item => new { item.Name, item.age })
                  .Select(group => group.First()).ToList();

Find not matched items from pets and pets2 .
var notMatchedpets = pets.Where(p2 => !pets2.Any(p1 =>
                     p1.Name == p2.Name && p1.age == p2.age)).ToList();

Now let’s group the pets sum their ages and order them Descending.
var groupPetWithAgeSum = pets.GroupBy(x => x.Name)
                        .Select(x => new { Name = x.Key, TotalAge = x.Sum(y => y.age) })
                        .OrderByDescending(x => x.TotalAge).ToList();

Here what I am doing is creating a new pet for each pet in the pets,
the code looks so clean and easy to understand.
var newPets = pets.Select(pet => new pet 
             { Name = "New_pet_" + pet.GetHashCode(), age = 10 }).ToList();
MSDN Lambda Expressions and MSDN–IEnumerable<T>

You might also like