Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase index of array

Tags:

arrays

c#

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
}
like image 619
sparta93 Avatar asked Dec 20 '22 02:12

sparta93


1 Answers

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.

like image 110
Charles Mager Avatar answered Jan 03 '23 00:01

Charles Mager