Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

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

Posted by Paul on December 7, 2010

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)


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)




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.


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>();


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s