Using LINQ to remove elements from a Listlt;Tgt;(使用 LINQ 从列表中删除元素lt;Tgt;)
问题描述
假设我有 LINQ 查询,例如:
Say that I have LINQ query such as:
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
鉴于 authorsList
是 List
类型,我如何从 authorsList
Author 元素> 由查询返回到 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 从列表中删除元素<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 从列表中删除元素<T>


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01