使用LINQ从List <T>中移除元素

假设我有LINQ查询,例如:

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

鉴于authorsList是类型的List<Author> ,我怎样可以删除Author从要素authorsList由查询到返回authors

或者authorsList一种说法,我怎样才能从authorsList删除所有名字相同的Bob?

注意:这是针对该问题的简化示例。


那么,首先排除它们会更容易:

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

但是,这只会改变authorsList的值,而不是从以前的集合中删除作者。 或者,您可以使用RemoveAll

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

如果你真的需要基于另一个集合来做,我会使用HashSet,RemoveAll和Contains:

var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));

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

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

如果您确实需要删除项目,那么Except()如何呢?
您可以基于新列表进行删除,或者通过嵌套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/27831.html

上一篇: Using LINQ to remove elements from a List<T>

下一篇: Escaping two single quotes in JDBC PreparedStatement parameter