问题
I want to build a sublist with references to the elements of anoter list (i need few of them, that are meeting the conditions).
How am i trying to do that:
List<int> mainList = new List<int>();
List<int> subList = new List<int>();
mainList.Add(5);
subList.Add(mainList[0]); //case 1
//subList[0] = mainList[0]; //case 2
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
subList[0]++;
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
mainList[0]+=2;
Console.WriteLine("{0}", mainList[0]);
Console.WriteLine("{0}", subList[0]);
In the first case i'm getting the copy instead of reference because the console output is:
5
5
5
6
7
6
In the second case i'm getting ArgumentOutOfRangeException because subList[0]
is not initialized.
So, how can i do this?
Also, according to speed/memory usage may be it's even better to keep List<int>
of inedexes of the mainList instead of references?
回答1:
Thanks to @ManIkWeet and @Florian, i've found the solution:
public class TestClass{
public int value;
}
...
List<TestClass> mainList = new List<TestClass>();
List<TestClass> subList = new List<TestClass>();
mainList.Add(new TestClass { value = 5 });
subList.Add(mainList[0]);
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
subList[0].value++;
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
mainList[0].value+=2;
Console.WriteLine("{0}", mainList[0].value);
Console.WriteLine("{0}", subList[0].value);
Output is:
5
5
6
6
8
8
回答2:
Case 2: You can not assign the value in list when list is not containing any element because there is no memory allocalted to your list items in sublist.
you are getting the System.ArgumentOutOfRangeException because your list index is less than 0 or index is equal to or greater than list count
You can assign value via indexing when you have item in your list
Hope this help !
来源:https://stackoverflow.com/questions/48580529/c-sharp-list-of-references-to-another-list-elements