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?