Jean Paul's Blog

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

    Advertisements
  • 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 – To remove items in a list

Posted by Paul on December 5, 2010


I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

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

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

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

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

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

list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

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 )

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