开发者

How to match two array and keep the matched value into a new array using c#?

开发者 https://www.devze.com 2023-02-09 09:45 出处:网络
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++)

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.Leng开发者_高级运维th; 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消