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

772

假设我有一个LINQ查询,例如:

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

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

或者换一种方式,如何从authorsList中删除所有名为Bob的人的名字?

注意:这只是一个简化的例子。

14个回答

6
以下是从列表中移除元素的示例。
 List<int> items = new List<int>() { 2, 2, 3, 4, 2, 7, 3,3,3};

 var result = items.Remove(2);//Remove the first ocurence of matched elements and returns boolean value
 var result1 = items.RemoveAll(lst => lst == 3);// Remove all the matched elements and returns count of removed element
 items.RemoveAt(3);//Removes the elements at the specified index

5

我认为你可以做类似这样的事情

    authorsList = (from a in authorsList
                  where !authors.Contains(a)
                  select a).ToList();

虽然我认为已经给出的解决方案以更易读的方式解决了问题。

1
我认为你只需要将作者列表中的项目分配给一个新列表,就可以实现这个效果。
//assume oldAuthor is the old list
Author newAuthorList = (select x from oldAuthor where x.firstname!="Bob" select x).ToList();
oldAuthor = newAuthorList;
newAuthorList = null;

0
为了保持代码的流畅性(如果代码优化不是至关重要的话),并且您需要对列表进行进一步操作:
authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;

或者

authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接