使用LINQ to删除列表&LT元素; T> [英] Using LINQ to remove elements from a List<T>

查看:249
本文介绍了使用LINQ to删除列表&LT元素; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人说我LINQ查询,如:

Say that I have LINQ query such as:

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

由于 authorsList 的类型是名单,其中,作者> ,我怎么可以删除 authorsList 元素>是由查询返回到作者

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

Or, put another way, how can I delete all of the Bob's 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();

然而,这只会改变,而不是从previous集合中移除作者 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过并且包含:

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 to删除列表&LT元素; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆