Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"

Tags:

c#

For creating a list with 100 random number between 0 and 1 I wrote below code that I receive the error.

      public List<float> random()
        {
            List<float> storerandomvalues = new List<float>(100);
            Random randomvalues = new Random();
            float randomnum;
            for (int counter = 0; counter < 100; counter++)
            {
                randomnum = 0f;
                randomnum = randomvalues.Next(1);
                storerandomvalues[counter]= randomnum;           //the error
            }
            return storerandomvalues;
        }
like image 691
user3371238 Avatar asked Dec 28 '25 17:12

user3371238


1 Answers

You're creating empty storerandomvalues (without any items). Parameter in the List<> constructor is the list capacity only.

The best solution in your case is to use array instead of List<> (because in your case the number of items in the collection is constant):

var storerandomvalues = new int[100];
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < storerandomvalues.Length; counter++)
{
    randomnum = 0f;
    randomnum = randomvalues.Next(1);
    storerandomvalues[counter] = randomnum;        
}
return storerandomvalues;
like image 167
alexmac Avatar answered Dec 31 '25 09:12

alexmac