0

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])

Paul Viorel
  • 234
  • 1
  • 11

2 Answers2

0
var firstSet = first.ToHashSet();
var result = second.Where(x => firstSet.Contains(x)).ToArray();
Bob
  • 107
  • 6
0
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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142