Copy a List to another List without dependencies

2

How do I copy data from one list to another so that they are independent of one another? I have a < > of a class that I created where the data inserted in it, will appear in a listBox, and wanted to copy everything that is in that list to a new one. I managed to copy everything from one to another, but when I work with the second list, the original (first list) undergoes unwanted changes.

This is my class:

public class vao
{
    public int quantidade { get; set; }
    public double medida { get; set; }
}

This is how I am inserting the data into the list and making it displayed in the listbox.

    List<vao> vaos = new List<vao>();
    List<vao> ordenada = new List<vao>();

    private void button1_Click(object sender, EventArgs e)
    {
        vao A = new vao();
        A.quantidade = Convert.ToInt32(textBox1.Text);
        A.medida = Convert.ToDouble(textBox2.Text);
        vaos.Add(A);

        listBox1.Items.Clear();
        foreach (vao item in vaos)
        {
            listBox1.Items.Add(item.quantidade + " x " + item.medida);
        }

        textBox1.Text = "";
        textBox1.Focus();
        textBox2.Text = "";
    }

And this form is how I am copying everything from a list (vaos) to the list (sorted) and to display what is in the (sorted) list in a new listbox in the way that you would like.

private void button3_Click(object sender, EventArgs e)
    {
        ordenada = vaos;

        for (int i = 0; i <= ordenada.Count - 1; i++)
        {
            for (int j = i + 1; j < ordenada.Count; j++)
            {
                if (ordenada[i].medida < ordenada[j].medida)
                {
                    int aux_qt = ordenada[i].quantidade;
                    ordenada[i].quantidade = ordenada[j].quantidade;
                    ordenada[j].quantidade = aux_qt;

                    Double aux_med = ordenada[i].medida;
                    ordenada[i].medida = ordenada[j].medida;
                    ordenada[j].medida = aux_med;
                }
            }
        }

        listBox2.Items.Clear();
        foreach (var item in ordenada)
        {
            listBox2.Items.Add(item.quantidade + " x " + item.medida);
        }

    }

InthiscaseIenteredthequantitiesandmeasurementsandcopiedandsorted.

WhenIselectanindexfromtheOriginallist,thevaluestheyhavearetheonesthatareintheSortlist

    
asked by anonymous 16.12.2016 / 01:39

2 answers

2

When assigning a list to the other list in the traditional way ex: listA = listB. TheA list will reference the same memory space as listB. With this, any change of the objects of one of the lists will be changed in the other list. The workaround would be to define a new location in memory for the A list.

One possible solution would be to create a class with the [Serializable] attribute. Ex:

[Serializable]
public class Carro
{
     public int Codigo { get; set; }
     public string Marca { get; set; }
     public decimal Preco { get; set; }
     public bool AirBag { get; set; }
}

Create a method for Cloning Objects.

public static object ClonarObjeto(object objRecebido)
{
    using (var ms = new System.IO.MemoryStream())
    {
        var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        bf.Serialize(ms, objRecebido);
        ms.Position = 0;

        object obj = bf.Deserialize(ms);
        ms.Close();

        return obj;
    }
}

At last clone the objects:

List<Carro> listaCarros = new List<Carro>();
List<Carro> listaCarrosCopia = new List<Carro>();

listaCarros.Add(carroA);
listaCarros.Add(carroB);

foreach (Carro item in listaCarros)
    listaCarrosCopia.Add((Carro)ClonarObjeto(item));

We will now have two separate lists.

    
16.12.2016 / 14:07
3

It makes LINQ easier:

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main(string[] args) {
        var vaos = new List<Vao> {new Vao {Quantidade = 2, Medida = 2}, new Vao {Quantidade = 0, Medida = 0}, new Vao {Quantidade = 1, Medida = 1}};
        var ordenada = new List<Vao>(vaos);
        ordenada = vaos.OrderBy(p => p.Medida).Select(item => item.Clone()).ToList();
        ordenada[1].Medida = 5;
        foreach (var item in ordenada) {
            WriteLine($"{item.Quantidade} x {item.Medida}");
        }
        foreach (var item in vaos) {
            WriteLine($"{item.Quantidade} x {item.Medida}");
        }
    }
}

public class Vao {
    public int Quantidade { get; set; }
    public double Medida { get; set; }
    public Vao Clone() {
        return (Vao)this.MemberwiseClone();
    }
}

See working at dotNetDiffle and on CodingGround .

There are a lot of bad things in this code, but what was asked is there.

    
16.12.2016 / 01:54