I'd like to use nested lists in my data acquistion application to store my incoming 16bit data dynamically. I created a list of UInt16 and added it three times (NUMCHANNEL=3) to a List type list. Now I expect that I can add an Uint16 entry the way the code shows below:
public List<UInt16> TBATT16 = new List<UInt16>();
public List<List<UInt16>> LBATT16 = new List<List<UInt16>>();
for (int i = 0; i < NUMCHANNEL; ++i)
{
LBATT16.Add(TBATT16);
}
LBATT16[0].Add((ushort)(0x1155));
It do add an entry but not only to the LBATT16[0] but to all LBATT16 lists. What am I doing wrong here?
You need to move your list creation inside the loop:
public List<List<UInt16>> LBATT16 = new List<List<UInt16>>();
for (int i = 0; i < NUMCHANNEL; ++i)
{
//Make a unique list for each element
public List<UInt16> TBATT16 = new List<UInt16>();
LBATT16.Add(TBATT16);
}
LBATT16[0].Add((ushort)(0x1155));
Because you have only one TBATT16 - this is a reference type, meaning that in your for loop you're not actually adding new empty list each time, you're just adding the same list over and over again. And then it doesn't matter which reference do you pick - you get the same inner list all the time.
Replace TBATT16 in your loop body with new List<UInt16>() and it'll work as you expect.
For more info on references in C#, see for example this article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With