Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get common elements in lists in C#

Tags:

c#

linq

I have two sorted lists as below:

var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };

I want the output to be: {1, 1, 2}

How to do this in C#? Is there a way using Linq?

like image 535
Manoj Pandey Avatar asked Oct 09 '12 15:10

Manoj Pandey


People also ask

How do you find common elements in a list?

With reduce and lambda This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them .

How do you find common elements in multiple lists?

You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.


2 Answers

Use Intersect:

 var commonElements = list1.Intersect(list2).ToList();
like image 91
Mahmoud Gamal Avatar answered Oct 07 '22 01:10

Mahmoud Gamal


The extra 1 means you can't use Intersect because it returns a set.

Here's some code that does what you need:

var list1 = new List<int>() { 1, 1, 1, 2, 3 };
var list2 = new List<int>() { 1, 1, 2, 2, 4 };

var grouped1 =
    from n in list1
    group n by n
    into g
    select new {g.Key, Count = g.Count()};

var grouped2 =
    from n in list2
    group n by n
    into g
    select new {g.Key, Count = g.Count()};

var joined =
    from b in grouped2
    join a in grouped1 on b.Key equals a.Key
    select new {b.Key, Count = Math.Min(b.Count, a.Count)};

var result = joined.SelectMany(a => Enumerable.Repeat(a.Key, a.Count));

CollectionAssert.AreEquivalent(new[] {1, 1, 2}, result);
like image 41
Austin Salonen Avatar answered Oct 07 '22 03:10

Austin Salonen