Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two List<string> and print the duplicates

Tags:

c#

linq

I'm having trouble preserving the duplicates when comparing two List<T> objects. The goal is to have the duplicates added to a third list, call it list3.

list1 has about 5 items, while list2 has 10 items.

list3 should contain the following: 00T51234, 00T54567, 00T57894

List<string> list1 = new List<string>(){"00T51234", "00T54567", "00T57894",
                     "00T55263", "00T58965"};

List<string> list2 = new List<string>(){"00T59633", "00T52222", "00T57894", 
                     "00T52322", "00T51234", "00T54567", "00T57894", "00T57897",
                     "00T55556", "00T59563"};

List<string> list3 = new List<string>();

I attempted to use Ani's resolution, seen below:

var lookup2 = list2.ToLookup(str => str);

var result = from str in list1
         group str by str into strGroup
         let missingCount 
              = Math.Max(0, strGroup.Count() - lookup2[strGroup.Key].Count())
         from missingStr in strGroup.Take(missingCount)
         select missingStr;

However this solution is not giving me the result that I'm looking for. Any help would be greatly appreciated. Thanks!

like image 359
toose121 Avatar asked Jan 15 '14 21:01

toose121


1 Answers

Use Enumerable.Intersect method

List<string> duplicates = list1.Intersect(list2).ToList();
like image 166
Sachin Avatar answered Oct 07 '22 20:10

Sachin