假设我有这样的LINQ查询:

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

假设authorsList的类型是List<Author>,我如何从authorsList中删除查询返回的Author元素?

或者,换句话说,我如何从authorsList中删除所有与Bob相同的firstname ?

注意:这是一个简化的例子,以方便提问。


当前回答

假设authorsToRemove是一个IEnumerable<T>,其中包含您想从authorsList中删除的元素。

下面是另一种非常简单的方法来完成OP要求的移除任务:

authorsList.RemoveAll(authorsToRemove.Contains);

其他回答

简单的解决方案:

static void Main()
{
    List<string> myList = new List<string> { "Jason", "Bob", "Frank", "Bob" };
    myList.RemoveAll(x => x == "Bob");

    foreach (string s in myList)
    {
        //
    }
}

LINQ起源于函数式编程,它强调对象的不可变性,因此它不提供内置的方式来就地更新原始列表。

关于不可变性的注意事项(来自另一个SO答案):

这是维基百科对不变性的定义。

在面向对象和函数式编程中,不可变对象是 创建后状态不可修改的对象。

我认为你只需要将作者列表中的项目分配到一个新的列表中就可以了。

//assume oldAuthor is the old list
Author newAuthorList = (select x from oldAuthor where x.firstname!="Bob" select x).ToList();
oldAuthor = newAuthorList;
newAuthorList = null;

你可以用两种方法去除

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;

我也有同样的问题,如果你想根据你的where条件简单输出,那么第一个解决方案更好。

最好使用List<T>。RemoveAll来完成这个任务。

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