在列表2从列表中1项不 [英] Remove items from list 1 not in list 2
本文介绍了在列表2从列表中1项不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我学习写 lambda表达式的,我需要如何删除所有帮助。从没有在其他列表中的列表元素
VAR名单=新名单,LT; INT> {1,2,2,4,5};
变种列表2 =新的List< INT> {4,5};
//删除所有列表项不在列表2
//新的列表应包含{4,5}
// Lambda表达式是谓词。
list.RemoveAll(项目=方式>项/ *解决方案表达这里* /);
//显示结果。
的foreach(INT我的列表)
{
Console.WriteLine(一);
}
解决方案
您可以通过removeall过这样做使用包括:
list.RemoveAll(!项目= GT; list2.Contains(项目));
另外,如果你只是想路口,使用的Enumerable.Intersect 会更有效:
列表= list.Intersect(列表2).ToList();
不同的是,在后一种情况下,将不会得到重复条目。例如,如果列表2
含有2,在第一种情况下,你会得到 {2,2,4,5}
,在第二,你会得到 {2,4,5}
。
I am learning to write lambda expressions, and I need help on how to remove all elements from a list which are not in another list.
var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };
// Remove all list items not in List2
// new List Should contain {4,5}
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
解决方案
You can do this via RemoveAll using Contains:
list.RemoveAll( item => !list2.Contains(item));
Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient:
list = list.Intersect(list2).ToList();
The difference is, in the latter case, you will not get duplicate entries. For example, if list2
contained 2, in the first case, you'd get {2,2,4,5}
, in the second, you'd get {2,4,5}
.
这篇关于在列表2从列表中1项不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文