How to get array overlap using LINQ?

Suppose I have the following arrays:

List<int[]> numbers = new List<int[]>(); numbers.Add(new int[] { 1, 2, 3 }); numbers.Add(new int[] { 3, 4, 5 }); numbers.Add(new int[] { 5, 6, 7 }); int[] numbersToFind = new int[] { 4, 5, 6 }; 

I want to find which of the numbers elements contains one or more values ​​in numbersToFind , is there an easy way to do this with LINQ? That is, some code that returns an IEnumerable<int[]> containing int[]{3,4,5} and int[]{5,6,7} in the above example.

How can I do that?

+4
source share
5 answers
 numbers.Where(array => array.Any(value => numbersToFind.Contains(value))); 
+7
source

Try the following:

 var query = numbers.Where(n => numbersToFind.Any(x => n.Contains(x))); 

Here's an alternative approach using the Enumerable.Intersect method:

 var query = numbers.Where(n => numbersToFind.Intersect(n).Any()); 
+5
source
 IEnumerable<int[]> matches = numbers.Where(n => numbersToFind.Intersect(n).Any()); 
+3
source

There is a LINQ Intersect function for this:

numbers.Intersect(numbersToFind)

+2
source

Try the following:

 numbers.Where(a => a.Any(s => numbersToFind.Contains(s))); 

Good luck

+1
source

All Articles