How to create LINQ condition with an int Array?

Viewed 29

I've got 2 arrays of Int, and I want to keep only elements from second array that contains the first array elements.

int [] first = new int[2]  { 1,  2};
int [] second = new int[5]  { 99,  1, 2, 97, 95};

I have tried something like below.

foreach(int x in first){
second.Where(s=>s==x);
}

But it doesn't help me because I need to compare both elements from first array

second.Where(s=>s==x[0] && s[1])

and if the int is bigger I need. Do you have any ideas how to get below code line?

second.Where(s=>s==x[0] && s== x[1] && ... && s==x[n])

2 Answers
var firstSet = first.ToHashSet();
var result = second.Where(x => firstSet.Contains(x)).ToArray();
var elements = second.Where(first.Contains);

Maybe materialize it with a .ToList() or ToArray() call.

If the first list is really large, you could think about a faster version than the .Contains method, but for your lists, it would be overkill.

Related