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);
}
}
In this case I entered the quantities and measurements and clicked to copy and sort.
When I select an index from the Original list the values you have are the ones in the Sorted list
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 ?
– Diogo Sousa
@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.
– Maniero
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
– Diogo Sousa