简体   繁体   中英

Delete Element from Array Using For Loop + If Statement - C#

I Have an array, TempArray[] = {1,3,-1,5,7,-1,4,10,9,-1}

I want to remove every single -1 from this array and copy the remaining arrays into a new array called Original, which should output the numbers as 1,3,5,7,4,10,9

I can only use an if statement within a for loop!

This is what I have so far, but I keep getting an error message, 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];
            }
        }

If you can only use If statement in for loop. This looks like a school project. First you count how many non negative numbers are there in your array. Create new array with that length and fill that array.

int[] TempArray = new int[] {1,3,-1,5,7,-1,4,10,9,-1};
int[] Original ; 
int countNonNegative=0;
 for (int i = 0; i < TempArray.Length; i++)
{
            if (TempArray[i] != -1)
            {
                countNonNegative++;
            }
 }
    Original = new int[countNonNegative];
    int index=0;
    for (int i = 0; i < TempArray.Length; i++)
    {
            if (TempArray[i] != -1)
            {
                Original[index] = TempArray[i];
                index++;
            }
    }
    Console.WriteLine("Original Length = "+Original.Length);
 using System.Linq;

 int[] withoutNegativeOnes = myArray
   .Where(a => a != -1)
   .ToArray();
var Original = new int[TempArray.Length];
var originalCounter = 0;

for (int i = 0; i < TempArray.Length; i++)
{
    if (TempArray[i] != -1)
    {
        Original[originalCounter++] = TempArray[i];
    }
}

Now Original may contain empty spaces at the end though, but you have all the elements which aren't -1. You can use the following code to iterate through the values:

for (int i = 0; i < originalCounter; i++)
{
    Console.WriteLine(Original[i]);
}

and that's because the originalCounter has the last index values that wasn't filled from TempArray 's iteration.

try this one

int[] TempArray = { 1, 3, -1, 5, 7, -1, 4, 10, 9, -1 };

int[] original = TempArray.Where(i => i != -1).ToArray();

foreach(int i in original)
   Console.WriteLine(i.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM