Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to remove elements from a List<T>

Tags:

c#

.net

list

linq

Say that I have LINQ query such as:

var authors = from x in authorsList               where x.firstname == "Bob"               select x; 

Given that authorsList is of type List<Author>, how can I delete the Author elements from authorsList that are returned by the query into authors?

Or, put another way, how can I delete all of the firstname's equalling Bob from authorsList?

Note: This is a simplified example for the purposes of the question.

like image 642
TK. Avatar asked May 12 '09 15:05

TK.


People also ask

How do I delete a record in LINQ query?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.

How do I delete multiple records in LINQ?

You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class. Show activity on this post. First, you can find a list of the items you want to delete.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


2 Answers

Well, it would be easier to exclude them in the first place:

authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList(); 

However, that would just change the value of authorsList instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll:

authorsList.RemoveAll(x => x.FirstName == "Bob"); 

If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:

var setToRemove = new HashSet<Author>(authors); authorsList.RemoveAll(x => setToRemove.Contains(x)); 
like image 134
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet


It'd be better to use List<T>.RemoveAll to accomplish this.

authorsList.RemoveAll((x) => x.firstname == "Bob"); 
like image 22
Reed Copsey Avatar answered Sep 22 '22 21:09

Reed Copsey