Steven Wood
Steven Wood

Reputation: 2785

Comparing two Lists and returning the distinct values and the differences

I have two lists:

List A {A, B, C, D}

List B {A, E, F, G}

I need to produce three lists:

One with the items only in list A

(B, C, D)

One with the items only in list B

(E, F, G)

One with the items in both

(A)

Given that the lists are actually registry keys, there could be a huge number of them so I can foresee a huge performance overhead if I choose to use traditional ForEach or For(int i...) methods.

I am not averse to these if they will do the job efficiently but I would prefer to use Linq.

Has anyone got any ideas?

I don't care about identical records.

I have already created an IEquatable<> class that will compare the elements, but it is how to use this to create my required outputs that I am struggling with.

Thanks in advance.

By the way I am using VS2012 with .NET 4.5

Upvotes: 16

Views: 13539

Answers (2)

roman
roman

Reputation: 117485

var A = new List<string>() { "A", "B", "C", "D" };
var B = new List<string>() { "A", "E", "F", "G" };

A.Except(B).ToList()
// outputs List<string>(2) { "B", "C", "D" }
B.Except(A).ToList()
// outputs List<string>(2) { "E", "F", "G" }
B.Intersect(A).ToList()
// outputs List<string>(2) { "A" }

Upvotes: 20

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

Using LINQ

listA.Except(listB) 

This will give you all of the items in listA that are not in listB..

For similar

listA.SequenceEqual(listB)

Upvotes: 6

Related Questions