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

Using LINQ to remove elements from a Listlt;Tgt;(使用 LINQ 从列表中删除元素lt;Tgt;)
本文介绍了使用 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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)