Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two sets of data in linq and return the common data?

I have two IList<string> a and b. I want to find out what strings are in both a and b using LINQ.

like image 304
kurasa Avatar asked Jan 21 '23 23:01

kurasa


1 Answers

Use Intersect:

Produces the set intersection of two sequences.

a.Intersect(b)

Example usage:

IList<string> a = new List<string> { "foo", "bar", "baz" };
IList<string> b = new List<string> { "baz", "bar", "qux" };

var stringsInBoth = a.Intersect(b);

foreach (string s in stringsInBoth)
{
    Console.WriteLine(s);
}

Output:

bar
baz
like image 50
Mark Byers Avatar answered Jan 24 '23 12:01

Mark Byers