ssl
ssl

Reputation:

find non intersecting data set with linq

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

output
1,3,4,5

Upvotes: 20

Views: 8273

Answers (3)

&#199;ağdaş Tekin
&#199;ağdaş Tekin

Reputation: 16651

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));

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300669

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();

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564531

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));

Upvotes: 42

Related Questions