Say that I have LINQ query such as:
var authors = from x in authorsList
where x.firstname == \"Bob\"
select x;
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));
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);
}
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();
This is a very old question, but I found a really simple way to do this:
authorsList = authorsList.Except(authors).ToList();
Note that since the return variable authorsList
is a List<T>
, the IEnumerable<T>
returned by Except()
must be converted to a List<T>
.
You can remove in two ways
var output = from x in authorsList
where x.firstname != "Bob"
select x;
or
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
var output = from x in authorsList
where !authors.Contains(x)
select x;
I had same issue, if you want simple output based on your where condition , then first solution is better.
i think you just have to assign the items from Author list to a new list to take that effect.
//assume oldAuthor is the old list
Author newAuthorList = (select x from oldAuthor where x.firstname!="Bob" select x).ToList();
oldAuthor = newAuthorList;
newAuthorList = null;