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 the items that are missing when comparing two collections:
// Assign two arrays.
int[] array1 = { 1, 2, 3 };
int[] array2 = { 2, 3, 4 };
// Call Intersect 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: 1, 4
}
As stated, if you want to get 4 as the result, you can do like this:
If you want the real non-intersection (also both 1 and 4), then this should do the trick:
This will not be the most performant solution, but for small lists it should work just fine.
You can use
Or you can use
This code enumerates each sequence only once and uses
Select(x => x)
to hide the result to get a clean Linq-style extension method. Since it usesHashSet<T>
its runtime isO(n + m)
if the hashes are well distributed. Duplicate elements in either list are omitted.array1.NonIntersect(array2);
Nonintersect such operator is not present in Linq you should do
except -> union -> except
I think you might be looking for
Except
:Check out this link, this link, or Google, for more information.