Nemo
Nemo

Reputation: 203

Divide array into parts into list of list

I am trying to divide array called "UWeights" to small parts and store them into list of list. The size of each part is stored in array called "Noofelement".
So i wrote the following code for doing this task but there is an exception fired with this title "Index was out of range. Must be non-negative and less than the size of the collection" but i don not know what is the problem.

     List<List<int>> unknownvalues=new List<List<int>>();

     int stindx = 0;
     int loopiteration = 0;
        for (int i = 0; i < 4; i++)
        {
            int nofelement = Noofelement[i];
            while (loopiteration < nofelement)
            {
                unknownvalues[i] = new List<int>();
                unknownvalues[i].Add((int)UWeights[stindx]);
                loopiteration++;
                stindx++;
            }
            loopiteration = 0;
        }

this is the exception, it happened in the line of list of list stindx,Noofelement and UWeights are correct

Is this the right way to define list of list and add to list of list?

List<List<int>> unknownvalues=new List<List<int>>();

unknownvalues[i] = new List<int>();
unknownvalues[i].Add((int)UWeights[stindx]);

Any help
Thanks in advance

Upvotes: 0

Views: 55

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156624

unknownvalues is being initialized as an empty list, and nothing is getting added into it, so i will always be outside the range of values that's in the list.

You can use unknownvalues.Add(new List<int>()) instead of unknownvalues[i] = new List<int>().

Upvotes: 1

Related Questions