[英]Return exclusive elements from two lists that comes more than twice using linq
I have two lists:我有两个清单:
int[] List1 = { 10, 10029, 30, 30, 10030 };
int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };
and the following statement,以及以下声明,
var NewList = List1.Except(List2);
returns返回
10
30
but I want the output to include the exclusive elements that have been duplicated.但我希望 output 包含已复制的专有元素。 So,
所以,
10
30
30
LINQ with the semantics you're looking for: LINQ 具有您正在寻找的语义:
var newList = List1.Where(x => !List2.Contains(x));
Note that this is quadratic in the size of the lists.请注意,这是列表大小的二次方。 If the lists are large then this might take a long time.
如果列表很大,那么这可能需要很长时间。 To alleviate that, you can turn the other list to a set first, for fast lookup:
为了缓解这种情况,您可以先将另一个列表转换为一个集合,以便快速查找:
var list2AsSet = List2.ToHashSet();
var newList = List1.Where(x => !list2AsSet.Contains(x));
Use the Contains
method to determine if the element exist in the second list使用
Contains
方法确定元素是否存在于第二个列表中
int[] List1 = { 10, 10029, 30, 30, 10030 };
int[] List2 = { 14,22,23,24,25,26,2728,29,10029,10030 };
var exclusive = List1.Where(x => !List2.Contains(x));
foreach (var el in exclusive){
Console.WriteLine(el);
}
More about Contains
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=net-6.0更多关于
Contains
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=net-6.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.