我有一個數組,TempArray [] = {1,3,-1,5,7,-1,4,10,9,-1}從數組中刪除元素使用For循環+如果語句 - C#
我想從這個數組中刪除每一個-1,並將其餘數組複製到一個名爲Original的新數組中,該數組應該輸出數字爲1,3,5,7,4,10,9
我可以僅在for循環中使用if語句!
這是我到目前爲止,但我不斷收到錯誤消息,System.IndexOutOfRangeException
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
//error occurs at this line
//My attempt is to set the new array, Original[i] equal to TempArray[i] only where the values are not -1.
TempArray[i] = Original[i];
}
}
除非您有充分的理由使用數組,否則應該使用列表。 –