与 Intersect() 相反 [英] The opposite of Intersect()

查看:27
本文介绍了与 Intersect() 相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Intersect 可用于查找两个集合之间的匹配项,如下所示:

Intersect can be used to find matches between two collections, like so:

// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect extension method.
var intersect = array1.Intersect(array2);
// Write intersection to screen.
foreach (int value in intersect)
{
    Console.WriteLine(value); // Output: 2, 3
}

然而,我想实现的是相反的目标,我想列出一个集合中另一个集合中缺少的项目:

However what I'd like to achieve is the opposite, I'd like to list items from one collection that are missing from the other:

// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call "NonIntersect" extension method.
var intersect = array1.NonIntersect(array2); // I've made up the NonIntersect method
// Write intersection to screen.
foreach (int value in intersect)
{
    Console.WriteLine(value); // Output: 4
}

推荐答案

如前所述,如果你想得到 4 作为结果,你可以这样做:

As stated, if you want to get 4 as the result, you can do like this:

var nonintersect = array2.Except(array1);

如果你想要真正的非交集(也是 1 和 4),那么这应该可以解决问题:

If you want the real non-intersection (also both 1 and 4), then this should do the trick:

var nonintersect = array1.Except(array2).Union( array2.Except(array1));

这不会是最高效的解决方案,但对于小型列表,它应该可以正常工作.

This will not be the most performant solution, but for small lists it should work just fine.

这篇关于与 Intersect() 相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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