Timujin
Timujin

Reputation: 181

List<List> confusion

snippets of my code

List<List<optionsSort>> stocks = new List<List<optionsSort>>();
optionsSort tempStock1 = new optionsSort();
List<optionsSort> stock = new List<optionsSort>();

then some code,

for (int j = 1; j < optionsSt.Count; j++)
{

            if (optionsSt[j].isin == optionsSt[j - 1].isin)
            {

                tempStock1.name = optionsSt[j].name;
                tempStock1.date = optionsSt[j].date;
                tempStock1.strike = optionsSt[j].strike;
                tempStock1.size = optionsSt[j].size;
                tempStock1.isin = optionsSt[j].isin;
                tempStock1.callPut = optionsSt[j].callPut;

                stock.Add(tempStock1);

            }
            else
            {

                stocks.Add(stock);

                k = k + 1;
                stock.Clear();

                tempStock1.name = optionsSt[j].name;
                tempStock1.date = optionsSt[j].date;
                tempStock1.strike = optionsSt[j].strike;
                tempStock1.size = optionsSt[j].size;
                tempStock1.isin = optionsSt[j].isin;
                tempStock1.callPut = optionsSt[j].callPut;

                stock.Add(tempStock1);



            }




        }//endfor

Basicly, im going through a large list to sort elements into groups, a new List name stocks.

now the problem is, when I add to stocks all elements contained in the list stock and then clear stock on the next line to start again, I delete all the elements I have stored in stocks.

Any Ideas. Do I have to index stocks like stocks[i].Add(stock) so each block of similar stocks is an element in stocks.

Thanks for any help.

Upvotes: 2

Views: 113

Answers (2)

Kendall Frey
Kendall Frey

Reputation: 44326

You're not creating a new list, you're using one list, and filling it and clearing it repeatedly. Since your outer list contains only one list, repeated multiple times, that list will have the same contents in every instance. That is, when you clear your list, you can no longer access the old contents, even if you try to access them from inside the outer list.

What you need to do is to change this line:

stock.Clear();

To this:

stock = new List<optionsSort>();

That is what you really meant. :)

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149020

The problem is that List<T> objects, like all classes in .NET, are reference types. That means that every time you add stock to stocks you aren't adding a new list, you are only adding a reference to the same list in memory. So when you later call Clear, that is reflected both in your variable stock and in all other references in stocks.

You can resolve this by making a shallow copy of stock every time you add it to stocks:

stocks.Add(stock.ToList());

Upvotes: 3

Related Questions