TK. TK. - 1 year ago 64
C# Question

Using LINQ to remove elements from a List<T>

Say that I have LINQ query such as:

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

Given that
is of type
, how can I delete the
elements from
that are returned by the query into

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

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

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download