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>


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01