Using LINQ to remove elements from a List<T>
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));
It'd be better to use List<T>.RemoveAll to accomplish this.
authorsList.RemoveAll((x) => x.firstname == "Bob");
If you really need to remove items then what about Except()?
You can remove based on a new list, or remove on-the-fly by nesting the Linq.
var authorsList = new List<Author>()
{
new Author{ Firstname = "Bob", Lastname = "Smith" },
new Author{ Firstname = "Fred", Lastname = "Jones" },
new Author{ Firstname = "Brian", Lastname = "Brains" },
new Author{ Firstname = "Billy", Lastname = "TheKid" }
};
var authors = authorsList.Where(a => a.Firstname == "Bob");
authorsList = authorsList.Except(authors).ToList();
authorsList = authorsList.Except(authorsList.Where(a=>a.Firstname=="Billy")).ToList();
You cannot do this with standard LINQ operators because LINQ provides query, not update support.
But you can generate a new list and replace the old one.
var authorsList = GetAuthorList();
authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();
Or you could remove all items in authors
in a second pass.
var authorsList = GetAuthorList();
var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();
foreach (var author in authors)
{
authorList.Remove(author);
}