# How to compare two lists?

There are two lists
``````var lst1 = new List<string>(){"1","2","3"};
var lst2 = new List<string>(){"4","2","3"};</string></string>``````

Using Intersect I bring those elements that are repeated but I would like to know how many times each element is repeated.

``var rez = lst1.Intersect(lst2); // here the result is 2 and 3``

And I would like so
`var rez = lst1.Method(lst2)`
2 found 2 times
3 occurs 2 times.
July 9th 19 at 13:56
July 9th 19 at 13:58
First, determine which elements coincide in a separate list (using Intersect). And then in the loop check whether each element required of the list this checklist (using Contains).
July 9th 19 at 14:00
You can record the result Interselect in the dictionary element is the number of occurrences, then run in a loop through the worksheets, counting a specific number. Something like
``````var lst1 = new List<string>(){"1", "2", "3"};
var lst2 = new List<string>(){"4", "2", "3"};

var intersect = new List<string>(lst1.Intersect(lst2));
var res = new Dictionary<string, int32>();

foreach (var el in lst1)
if (res.ContainsKey(el))
res[el]++;
foreach (var el in lst2)
if (res.ContainsKey(el))
res[el]++;

foreach (var el in res)
Console.WriteLine("{0}: {1} time(s)", el.Key, el.Value);</string></string></string></string>``````
Optimization: to throw interselect, go to sheets, if the dictionary does not contain element, add a value of 1, otherwise increment. Then throw away anyone the number <2. Like it should be faster, but still a lot of operations with lists. - Sister.OConner74 commented on July 9th 19 at 14:03

Find more questions by tags C#