-1

I'm looking for a method to satisfy the need to insert a value in a index and if that index is busy all the next values of the array will slide down:

            char[] myArray = new char[5];

            myArray[0] = 'a';
            myArray[1] = 'b';
            myArray[2] = 'c';
            myArray[3] = 'd';
            myArray[4] = 'e';

            char missingChar = 'k';

            //I want to insert the char "missingChar" in myArray[2]
            //I want all the other indexes to move down, the former-myArray[2] also

                Array.Resize(ref myArray, myArray.Length + 1);

                myArray[0] = 'a';
                myArray[1] = 'b';
                myArray[2] = missingChar;
                myArray[3] = 'c';
                myArray[4] = 'd';
                myArray[5] = 'e';

The output desired is:

a, b, k, c, d, e

Is there a way to do this without involving lists?

  • 1
    You can do this pretty easily with List, and use of its Insert method. You can then use ToArray to return the list to an array. – Russ Jan 12 '21 at 17:41
  • 1
    @JohnnyMopp you may notice that OP is well aware of need to `.Resize` the array... – Alexei Levenkov Jan 12 '21 at 17:47
  • Don't use ToArray like that... https://github.com/juliusfriedman/net7mma_core/blob/master/Common/Extensions/StringExtensions.cs#L315 Do not use arrays like that period. – Jay Jan 12 '21 at 17:48

1 Answers1

0

Lists will handle this for you by dynamically resizing the backing arrays as needed.

var myArray = new List<char>(5);

myArray.Insert(0, 'a');
myArray.Insert(1, 'b');
myArray.Insert(2, 'c');
myArray.Insert(3, 'd');
myArray.Insert(4, 'e');

char missingChar = 'k';
    
myArray.Insert(2, missingChar);

This outputs:

a 
b 
k 
c 
d 
e 
David L
  • 32,885
  • 8
  • 62
  • 93