使用 LINQ 从列表中删除元素<T> [英] Using LINQ to remove elements from a List<T>

查看:39
本文介绍了使用 LINQ 从列表中删除元素<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 LINQ 查询,例如:

Say that I have LINQ query such as:

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

鉴于 authorsListList 类型,我如何从 authorsListAuthor 元素> 由查询返回到 authors?

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?

或者,换一种说法,如何从 authorsList 中删除所有与 Bob 相同的名字?

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

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

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

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

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

这篇关于使用 LINQ 从列表中删除元素&lt;T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆