I have an array for example
string[] data = {"1","2","3","5","6","7","4",....goes on)
Let's say I want to do the following operation; if the 3rd element of array data is 5
then move everything up the index one spot, basically the array would then become
{"1","2","3","","5","6","7","4"...}
and a blank space will take 5's place.
if (data[3] == "5")
{
// move index forward one spot
}
While this can be done with an array, it will probably prove easier to use some higher-level construct like List<T>
and then convert this back to an array should you need it. If you don't require an array at all you can just use List<T>
on its own.
string[] data = {"1","2","3","5","6","7","4"};
var list = new List<string>(data);
for (var i = 0; i < list.Count; i++)
{
if (list[i] == "5")
{
list.Insert(i, "");
i++;
}
}
data = list.ToArray();
Here's a working demo: https://dotnetfiddle.net/lHzgFH
This is the simplest implementation, though it isn't the most efficient - see some of the other answers for alternate implmementations that may prove a better option for large data sets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With