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 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.


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

最好使用List <T> .RemoveAll来实现这一点。

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();
链接地址: http://www.djcxy.com/p/27832.html

上一篇: 如何识别恶意源代码?

下一篇: 使用LINQ从List <T>中移除元素