1

Dear all, How i match 2 array and keep the matched value into a new array using c#?

for (int j = 0; j < arrayA.Length; j++)
{
    for (int k = 0; k < arrayB.Length; k++)
    {
        if (arrayA[j] == arrayB[k])
        {               
            arrayB[k];
         //How i keep this matched record into a new array?
        }
    }
}

Another thing: Is their any short cut way to match 2 array and keep the record into a new array? Any kind heart. Please help.

2 Answers 2

8

Why don't use LINQ:

var matchingValues = arrayA.Intersect(arrayB).ToArray();

SIDE NOTE:
the resulting array will have distinct values.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't believe this'll match on the values at a particular index, it'll just return values that are in both arrays.
@Massif: Yes, but actually the OP's code compares any value in the first array with any value in the second one, not only the value at the same index. So I suppose is trying to implement an intersection...
good point... I must learn to re-activate brain before commenting.
5

Store it in a List<int> or any type you have. (I assume yours is int)

   List<int> list = new List<int>();
   for (int j = 0; j < arrayA.Length; j++)
        {
            for (int k = 0; k < arrayB.Length; k++)
            {
                if (arrayA[j] == arrayB[k])
                {               
                    list.Add(arrayB[k]); // HERE !!

                }
            }
        }

Now if you need to change it to an array, you can do at the end:

 int[] finalArray = list.ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.