从基于另一个列表的列表条件中删除某些元素 [英] Removing certain elements from list condition based on another list

查看:58
本文介绍了从基于另一个列表的列表条件中删除某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有linq的一个基本问题.尽管这可以通过重复循环来解决.我想知道如何在linq中完成此操作.

I am having a basic issue here with linq . Though this can be solved with repeated loops . I am trying to know how can this be done in linq .

我有两个清单.

List<string> a  = new List<string>{"a","b","c","d","e","f"};
List<string> b = new List<string> { "a", "b", "c", "x", "y", "z" };

我想与列表a和b中的任何元素进行比较.我想从b中删除该元素.换句话说,我想基于列表a中的比较从b中删除{"a","b","c"},并且只想在列表b中包含{"x","y","z"}.是否有一个语句linq可以解决这个问题?

I want to compare with list a and whichever element in b is found in a . I want to remove that element from b . In other words I want to remove {"a","b","c"} from b based on comparison from list a and want to contain only {"x","y","z"} in list b . Is there a single statement linq to solve this ?

推荐答案

(我确定这是几天前另一篇文章的副本,但我找不到它...)

(I'm sure this is a duplicate of another post just a few days ago, but I can't find it...)

如果需要进行修改,可以使用List<T>.RemoveAll:

If you need a modification in place, you can use List<T>.RemoveAll:

b.RemoveAll(x => a.Contains(x));

或更有效的方法(如果列表很大):

Or more efficiently (if the lists are large):

HashSet<string> set = new HashSet<string>(a);
b.RemoveAll(set.Contains);

请注意,在LINQ中就地修改集合并不是惯用的,这就是为什么上面的方法使用特定于.NET 2列表的方法的原因.

Note that modifying a collection in place isn't idiomatic in LINQ, which is why the above uses the .NET 2 list-specific method.

或者,如果您愿意更改b来引用新列表,然后,则可以使用LINQ:

Or if you're happy to change b to refer to a new list instead, then you can use LINQ:

b = b.Except(a).ToList();

这篇关于从基于另一个列表的列表条件中删除某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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