How to traverse array values after inserting a value in a busy place

2

In a console application, where I have a string type arrangement, one of the operations allows inserting values in places that are occupied, for example: I have an array in the following way: {cero, uno, 0, 0 ,0} .

The zeros are null values, if you want to insert another value such as 'ncero' in the zero position, the current values must be traversed, being as follows:

{ncero, cero, uno, 0, 0}

The problem is when crossing it when they have more than one value occupied, if someone could help me.

if (respuesta == "2")
{
    bool señal = false;
    Console.Clear();
    Console.WriteLine("En que posicion desea insertar el dato?");

    respuesta = Console.ReadLine();//Lee el dato de manera String

    i = int.Parse(respuesta);//Convierte la posicion en tipo Int

    if (i > 9)//Si la posicion ingresada es mayor que el tamaño del array manda error
     Console.WriteLine("Ingrese una posicion valida");
    else
     Console.WriteLine("Ingrese el valor que desea agregar");
     respuesta = Console.ReadLine();//Lee el dato a ingresar

        if (Nombres[i] != null)//Si en la posicion deseada hay ya un valor
        {
          for (int x = i + 1; x < Nombres.Length; x++)//Recorre todo el arreglo

       {
    }
    
asked by Kevin M. 22.02.2016 в 21:13
source

1 answer

2

What I would recommend is that you do not use an array, but implement a List<> This type of list allows you to insert a value in the position you need.

It could be something like this

List<string> Nombres = List<string>();

// resto del codigo

if (i > 9)
{
    Console.WriteLine("Ingrese una posicion valida");
}
else
{
    Console.WriteLine("Ingrese el valor que desea agregar");
    respuesta = Console.ReadLine();//Lee el dato a ingresar

    if (Nombres[i] != null)//Si en la posicion deseada hay ya un valor
    {
        Nombres.Insert(i, respuesta)
    }
}

By using a list of accounts with a method

List.Insert (Method) (Int32, T)

When you need to work with collections where the position is dynamic, it is recommended that% is% of%

If you later need an array you could use the ToArray () on the list

    
answered by 22.02.2016 в 23:36