问题描述:

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.

网友答案:

Why don't use LINQ:

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

SIDE NOTE:
the resulting array will have distinct values.

网友答案:

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();
相关阅读:
Top