Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 253
Steven Wood Avatar asked Aug 07 '13 09:08

Steven Wood


People also ask

How do you compare two lists and print differences in Python?

Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.

How do you find the difference between two lists in Python?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .


2 Answers

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" }
like image 104
Roman Pekar Avatar answered Sep 22 '22 11:09

Roman Pekar


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)
like image 43
Vaibs_Cool Avatar answered Sep 19 '22 11:09

Vaibs_Cool