One Line Lambda-Lookup list of Lambda Expressions for common scenarios


I have observed that Lambda Expressions got good steam among developers. It helps us in reducing lot of code and save time.

I would like to list some of the useful Lambda Expressions here comparing with the without-lambda approach.

Common Setup Code

Here the common initialization code for using the below examples are given:

List<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

Scenario Lambda Approach Traditional Approach
Descending Sort list.OrderByDescending(i => i);

list.Sort(delegate(int x, int y)
    {
       
return y.CompareTo(x);
    });

Check all numbers are less than 100 bool result = list.All(i => i < 100);

bool result = true;
foreach (int i in list)
   
if (i >= 100)

        result = false;
Check any numbers are equal to 5 bool result = list.Any(i => i == 5);

bool result = false;
foreach (int i in list)
   
if (i == 5)

        result = true;
Get the top 5 items in the list var sublist = list.Take(3);

var sublist = new List<int>();
for (int i = 0; i < 5; i++)
   
if (i < list.Count)
        sublist.Add(i);

Sort descending, get all numbers less than 8, take the top 5 var result = list.OrderByDescending(i => i).Where(i => i < 8).Take(5);

list.Sort(delegate(int x, int y)

   
return y.CompareTo(x); 
});

List<int> result = new List<int>();

foreach (int i in list)

    if (i < 8)

        if (result.Count < 5)

            result.Add(i);

Summary

I think the examples above demonstrate how complex the code will look even if you do the simple sorting and selection.

Surely Lambda Expressions is worth learning and in the long run it would give more manageable code.

Note

In the sorting scenario above, the original list is not updated, OrderBy() will be giving a sorted view of the original list.

For assigning it back to the original list we have to use the ToList<int>() method as:

list = list.OrderByDescending(i => i).ToList<int>();

Up Next
    Ebook Download
    View all
    Learn
    View all