Say that I have LINQ query such as:

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

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?

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

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

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

.net相关问答推荐

为什么$NULL在ForEach-Object{}和Foreach()中的行为不同?

.NET Async / Await:状态机如何知道何时继续执行?

使用 PowerShell 从文件夹中获取文件名的最快\最好的方法是什么?

无法解析此引用.找不到程序集

为什么这两个比较有不同的结果?

.NET - WindowStyle = hidden 与 CreateNoWindow = true?

设置日志(log)文件名以在 Log4j 中包含当前日期

是否有任何 x 次的 for 循环的更短/更简单的版本?

支持 HTTPS 的 Httplistener

如何从 .NET 中的流中获取 MemoryStream?

如何在 C# 中以编程方式安装 Windows 服务?

如何防止任务的同步延续?

CI服务器的比较?

在 C# 中,为什么不能将 List 对象存储在 List 变量中

清除文件内容

.NET 委托类型的正确命名约定?

ValueTypes 如何从 Object (ReferenceType) 派生并且仍然是 ValueTypes?

obj 文件夹是为了什么而生成的?

C# ListView 列宽自动

泛型类的静态成员是否与特定实例相关联?