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

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

Leave a Reply

You May Also Like

C# Compiler Error CS0577 – The Conditional attribute is not valid on ‘function’ because it is a constructor, destructor, operator,...
There are times when you want your Application to play default Windows Sounds when an alert message is displayed . If...