Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match elements between 2 collections with Linq in c#

i have a question about how to do a common programming task in linq.

lets say we have do different collections or arrays. What i would like to do is match elements between arrays and if there is a match then do something with that element.

eg:

        string[] collection1 = new string[] { "1", "7", "4" };
        string[] collection2 = new string[] { "6", "1", "7" };

        foreach (string str1 in collection1)
        {
            foreach (string str2 in collection2)
            {
                if (str1 == str2)
                {
                    // DO SOMETHING EXCITING///
                }
            }
        }

This can obviously be accomplished using the code above but what i am wondering if there is a fast and neat way you can do this with LinqtoObjects?

Thanks!

like image 598
Grant Avatar asked Jan 25 '10 02:01

Grant


2 Answers

Yes, intersect - Code sample to illustrate.

string[] collection1 = new string[] { "1", "7", "4" };
string[] collection2 = new string[] { "6", "1", "7" };

var resultSet = collection1.Intersect<string>(collection2);

foreach (string s in resultSet)
{
    Console.WriteLine(s);
}
like image 89
Ragepotato Avatar answered Nov 17 '22 04:11

Ragepotato


If you want to execute arbitrary code on matches then this would be a LINQ-y way to do it.

var query = 
   from str1 in collection1 
   join str2 in collection2 on str1 equals str2
   select str1;

foreach (var item in query)
{
     // do something fun
     Console.WriteLine(item);
}
like image 42
Sam Avatar answered Nov 17 '22 04:11

Sam