jeudi 18 juin 2015

Sequence contains no elements

Can someone explain me why the following LINQ query throws an InvalidOperationException?
(Don't say that the list has no elements,the value that I'm looking for always exists in the collection)

class Program
{
     static int lastNumber;
     static void Main()
     {
          int loopCount = 100; int minValue = 1; int maxValue = 10000;
          var numbers = Enumerable.Range(minValue, maxValue).ToList();//or ToArray();
          Random random = new Random();

          for (int i = 0; i < loopCount; i++)
          {
              //.First() throws the exception but it is obvious that the value exists in the list
              int x = numbers.Where(v => v == NewMethod(minValue, maxValue, random)).First();
          }
          Console.WriteLine("Finished");
          Console.ReadLine();

     }

     private static int NewMethod(int minValue, int maxValue, Random random)
     {
         var a1 = random.Next(minValue + 1, maxValue - 1);
         lastNumber = a1;
         return a1;
     }
}

The problem appears only when I call NewMethod inside my lambda expession.
If do this it works

int temp=NewMethod(minValue, maxValue, random);
int x = numbers.Where(v => v == temp).First();

I added the lastNumber field to help debug the code,you can see that the value exists in the collection when it crashes

PS
The problem is not the random variable,I removed the parameter and create a new local random inside the method but the problem still exists




Aucun commentaire:

Enregistrer un commentaire