Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists to search common items

List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5

How to get all elements from one list that are present also in second list?

In this case should be: 1, 4

I talk of course about method without foreach. Rather linq query

like image 722
Saint Avatar asked Jul 31 '12 12:07

Saint


2 Answers

You can use the Intersect method.

var result = one.Intersect(second);

Example:

void Main()
{
    List<int> one = new List<int>() {1, 3, 4, 6, 7};
    List<int> second = new List<int>() {1, 2, 4, 5};

    foreach(int r in one.Intersect(second))
        Console.WriteLine(r);
}

Output:

1
4

like image 77
sloth Avatar answered Sep 25 '22 18:09

sloth


static void Main(string[] args)
        {
            List<int> one = new List<int>() { 1, 3, 4, 6, 7 };
            List<int> second = new List<int>() { 1, 2, 4, 5 };

            var result = one.Intersect(second);

            if (result.Count() > 0)
                result.ToList().ForEach(t => Console.WriteLine(t));
            else
                Console.WriteLine("No elements is common!");

            Console.ReadLine();
        }
like image 29
Dhanasekar Avatar answered Sep 23 '22 18:09

Dhanasekar