C # - Auxiliary copy of an arraylist

3

I have to make a selection of things, that is, I have {"A", "B", "c"} when I select one of the elements, this has to be accommodated in another new array that shows me the selected elements, for example I select "A" and this would be like this {"B", "C"} > > > > > {"A"}, this is what the problem is when I go back to the selection of elements to create a new combination, my elements of the first array are not reset, they remain the same {"B", "C"} the idea is that come back to being like {"A", "B", C "} to let me put together any combination.

Console.Clear();
        ArrayList listatermi2 = listatermi;
        Console.WriteLine("Seleccione las terminales del recorrido, ingrese 0 para finalizar");
        Console.WriteLine(" ");
        Console.WriteLine("[Lista de Terminales] ");


        for (int cont = 0; cont < listatermi2.Count; cont++)
        {
            Console.WriteLine("{0}) {1}",cont+1,listatermi2[cont]);
        }


        Console.WriteLine(" ");

        Console.WriteLine("Seleccione una opcion para armar recorrido");
        Console.WriteLine(" ");
        Console.WriteLine("[Recorrido Armado]");
        for (int cont = 0; cont < reco.Count; cont++)
        {
            Console.WriteLine(reco[cont]);
        }

        opcion = Console.ReadLine();
        if (opcion == "0")
        {
            menu();
        }
        reco.Add(listatermi2[int.Parse(opcion) - 1]);
        listatermi2.Remove(listatermi2[int.Parse(opcion)-1]);


        opcion3();

// note an original array has been declared, then when entering the option that allows me to create combinations I create a copy of the first one in this way every time you enter the option a copy of the original is created again

public static ArrayList listatermi = new ArrayList();
    
asked by Shiki 29.06.2017 в 15:57
source

1 answer

4

When you make ArrayList listatermi2 = listatermi; you are not actually creating a new ArrayList , but you are copying the reference of listatermi in listatermi2 . At that moment, listatermi and listatermi2 point exactly to the same position in memory, so any change made in one is immediately reflected in the other.

If you want to copy a list in the other, you must create a new ArrayList and copy the elements from one to the other, something like this:

ArrayList listatermi2= new ArrayList();
foreach (var item in listatermi)
{
    listatermi2.Add(item);
}

You can also use the Clone method:

ArrayList listatermi2=(ArrayList)listatermi.Clone();
    
answered by 29.06.2017 / 16:03
source