Copy a List to another List without dependencies

Asked

Viewed 5,175 times

3

How do I copy data from one list to another in a way that is independent of each other? I have a list<> of a class I created where the data inserted in it, appear in a listbox, and I wanted to copy everything that is in this list to a new one. I was able to copy everything from one to the other, 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’m putting the data on the list and making it presented 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 is how I’m copying everything from a list(vaos) to the list(Ordered) and to present what is in the list(sorted) in a new listbox in the way 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);
        }

    }

inserir a descrição da imagem aqui

In this case I entered the quantities and measurements and clicked to copy and sort. List já com dados

When I select an index from the Original list the values you have are the ones in the Sorted list inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

2 answers

4

Makes with LINQ it’s 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() => (Vao)this.MemberwiseClone();
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

There’s a lot of very inappropriate things in that code, but what was asked is there.

  • Thanks @bigown for your comment but it hasn’t solved my problem, it still has addiction. When the sorted list makes the changes, the index’s also change in the first one. By the way, what you think is inappropriate in my code ?

  • @Diogosousa I made a change to clone the object. I recommend you make a [mcve] to show the problem happening. There are several problems, in the code, everything small, if it were big would not work, but that will leave the bad code. This is not the focus here.

  • I have already put some images to try to show what is happening to me. I will try to do what you told me about cloning the object. Thank you

3


When you assign a list to the other list in the traditional way ex: listA = listB. The listA will reference the same memory space as the listB. With this any change of the objects of one of the lists will be changed in the other list. The solution would be to set a new memory location for the listA.

A 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 to Clone 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;
    }
}

Finally 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));

Now we’ll have two independent lists.

  • Thank you very much, it worked and it helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.