Here is the array
string[] Numbers = new string[5] { "1", "2", "", "3", "4" };
As you can see I have 1 item that has nothing in it. What I'm trying to do is make the array smaller and move, everything after the clear space, 1 down. I'm also going to use it for a bigger array. But it will always have just 1 clear space.
{"1", "2", "3", "4"}
This is what I'm trying to get.
Here are the variables
int intSelected, intCounter = 1, intAmount = Numbers.length;
And here is the code
while (true)
{
Numbers[intSelected intCounter] = Numbers[intSelected intCounter - 1];
if (intSelected intCounter == intAmount)
{
Array.Resize(ref Numbers, Numbers.Length - 1);
MessageBox.Show("It works");
intAmount--;
break;
}
else
{
intCounter ;
}
}
CodePudding user response:
One of the simplest ways to do it is to use System.Linq
to filter the undesired items out:
string[] Numbers = new string[5] { "1", "2", "", "3", "4" };
string[] ClearNumbers = Numbers.Where(e => !string.IsNullOrEmpty(e)).ToArray();
CodePudding user response:
No Linq solution (you've used Array.Resize
in your code; let's correct it). We scan the array, copy items on empty spaces and, finally, resize the array:
string[] Numbers = new string[5] { "1", "2", "", "3", "4" };
...
int lastIndex = 0;
for (int i = 0; i < Numbers.Length; i)
if (!string.IsNullOrEmpty(Numbers[i])) // if Numbers[i] should be preserved...
Numbers[lastIndex ] = Numbers[i]; // ... Copy it to the lastIndex place
Array.Resize(ref Numbers, lastIndex);