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 类型,我如何从 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 从列表中删除元素<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 从列表中删除元素<T>
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
