Intersect two List<int> having repeated values

c#

Solution

Try this:

List<int> result = list1.Where(i => list2.Contains(i)).ToList();

What this does is selects only the records in `list1` which exist in `list2`, which will result in an `IEnumerable<int>`. Then, the `ToList()` turns it back into a `List<int>`

The optimal version of this performance-wise is to convert `list2` to a `HashSet<int>` prior to the `Contains` call. This allows for faster lookups:

HashSet<int> hashSet = new HashSet<int>(list2);
List<int> result = list1.Where(i => hashSet.Contains(i)).ToList();

Problem

I have two lists of type int: ``` List<int> list1 = new List<int> {12,55,55,55,34}; List<int> list2 = new List<int> {12,55}; ``` If I intersect list1 with list2, then the expected result is `{12,55,55,55}`. How can I achieve this? Is there any other mean of achieving the same result?

Original source