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

output
1,3,4,5
Samuel
  • 37,778
  • 11
  • 85
  • 87

3 Answers3

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