首页 > 解决方案 > How add a List of Elements into a list without reference?

问题描述

I cannot find an answer because it seems too much specific. So here's my issue with C#. We can add another list to another one as a clone like this

list2 = new List<int>(list1);

What I want to know is how can I add a List into another one without any reference of the child?

List<List<List<int>>> wireCoords = new List<List<List<int>>>();
List<int> coord = new List<int>();

for(int i = 0; i < inputSplits.Length; i++)
 {
      coord.Add(0);
      coord.Add(0);
      wireCoords[i].Add(coord);

 }

AS soon the wireCoords[0][0] list change, it also change inside wireCoords[1][0] How can I fix this?

标签: c#

解决方案


Two things. You cannot access a List via [i] accessor unless it has content at that index. Second, you can copy the values of a list by using List1.AddRange(List2). After this, changing List2 will not change List1.

In your for loop, the number of items grow to inputSplits.Length * 2 for every index of wiredCoords. To explain why this happens, lets take an example.

List<int> object1 = new List<int>();
object1.Add(1);
object1.Add(2);

List<int> object2 = object1;

object1.Add(3);
// at this time, object2 also has an element 3.

Console.WriteLine(string.Join(",", object2));

output:
1,2,3 (instead of 1,2 that you'd normally expect)

object1 never gets assigned the "value" of object2. object1 will get "reference" of the object2 and anywhere in code when you change values of object1, object2 will automatically get updated.

Fix for that could be

List<int> object2 = object1;
object1 = new List<int>(); // re-initialized
object1.Add(3);

// object1 has only 1 element
// object2 has 2 elements.

To resolve this, you create a new object or re-initialize the object to get a new reference and then use that for later assignments.

Your code:

List<List<List<int>>> wireCoords = new List<List<List<int>>>();
List<int> coord ;

for(int i = 0; i < inputSplits.Length; i++)
 {
      coord = new List<int>();
      coord.Add(0);
      coord.Add(0);
      wireCoords.Add(coord);

 }

Hope it helps.


推荐阅读