List<int> a = 1,2,3
List<int> b = 2,4,5
output
1,3,4,5
Asked
Active
Viewed 7,598 times
20
-
Should 3 also be in the output? – Dave Apr 03 '09 at 01:04
-
I'm guessing yes... that would be in the non-intersecting data. – Reed Copsey Apr 03 '09 at 01:07
-
1This has a much better answer here https://stackoverflow.com/questions/5620266/the-opposite-of-intersect – Amicable Aug 24 '17 at 10:50
3 Answers
42
The trick is to use Except with the intersection of the two lists.
This should give you the list of non-intersecting elements:
var nonIntersecting = a.Union(b).Except(a.Intersect(b));

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
-
As I tested with a simple set it does not work. Though this solution works as stated by @Amicable in the original post : https://stackoverflow.com/questions/5620266/the-opposite-of-intersect – StackHola Feb 20 '19 at 15:14
4
Tried and tested:
List<int> a = new List<int>(){1, 2, 3};
List<int> b = new List<int>(){2, 4, 5};
List<int> c = a.Except(b).Union(b.Except(a)).ToList();

Mitch Wheat
- 295,962
- 43
- 465
- 541
0
Another way :
List<int> a = new List<int> { 1, 2, 3 };
List<int> b = new List<int> { 2, 4, 5 };
var nonIntersecting = a.Union(b)
.Where(x => !a.Contains(x) || !b.Contains(x));

Çağdaş Tekin
- 16,592
- 4
- 49
- 58