C# - How do I check if 2 arrays have one or more numbers in common?

Asked

Viewed 136 times

1

How do I find that in the numbers of 4 Textbox that are in the array numeros, are on the array impares or pares, what are these numbers and how many are odd and how many pairs?

int[] numeros = new int[] {text_box1, text_box2, text_box3, text_box4};
int[] pares = new int[] {02, 04, 06, 08, 10};
int[] impares =  new int[] {01, 03, 05, 07, 09};

1 answer

3


By strictly following the arrays of your question you can use the Intersect linq:

int[] numeros = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] pares = new int[] { 02, 04, 06, 08, 10 };
int[] impares = new int[] { 01, 03, 05, 07, 09 };

int[] inputsPares = numeros.Intersect(pares).ToArray();
int[] inputsImpares = numeros.Intersect(impares).ToArray();

int quantosPares = inputsPares.Length;
int quantosImpares = inputsImpares.Length;

For the problem in question, which consists only of checking whether it is even or odd, you can use the mod operator, so arrays are not required pares and impares.

int[] inputsPares = numeros.Where(x => x % 2 == 0).ToArray();
int[] inputsImpares = numeros.Where(x => x % 2 != 0).ToArray();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.