Remove All Objects matching the condition from a List using LINQ in C#

Are you using LINQ in C# and requite to remove all objects matching the condition from a List ? Read this blog post to find out how to delete all objects matching the condition from a List using LINQ.

How to Remove all the objects matching the condition from a List using LINQ ?

One can use the Remove method defined in the System.Collections.Generic.List class to delete or remove an object matching the condition .

The Remove method removes the first occurrence of the specific object from the List .

If you want to remove all the objects matching the condition from a List using LINQ , you can use the RemoveAll to delete all the occurrence of the objects that match the criteria.

In the below example , the movies contains the list of all movies which is ordered by the name of the actor and the movie name and is assigned to moviesLamba1 .

Then all the movies that has the actor name “hero1” is removed from the moviesLamba1 using the RemoveAll function and the lambda expression.

List<Movie> movies = new Movies();

var moviesLamba1 = movies.OrderBy(m => m.Actor).ThenBy(m => m.MovieName).ToList();

moviesLamba1.RemoveAll(x => x.Actor == "hero1");
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...