20
List<int> a = 1,2,3
List<int> b = 2,4,5

output
1,3,4,5
Samuel
  • 36,810
  • 11
  • 84
  • 86

3 Answers3

41

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
  • 539,124
  • 75
  • 1,126
  • 1,354
  • 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
  • 288,400
  • 42
  • 452
  • 532
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,432
  • 4
  • 48
  • 58