.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> .Net Framework >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expression to remove items from list

Posted By:Jean Paul       Posted Date: December 05, 2010    Points: 75    Category: .Net Framework    URL: http://www.dotnetspark.com  

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

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 list;

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

IList list = new List(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 list = new List(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

It takes only just 1 line of code to achieve the same.

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

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

// 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!!

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend