【发布时间】:2015-09-04 17:58:37
【问题描述】:
谁能解释一下为什么以下 LINQ 查询会引发 InvalidOperationException?
(不要说列表没有元素,我要找的值一直存在于集合中)
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;
}
}
只有当我在我的 lambda 表达式中调用 NewMethod 时才会出现问题。
如果这样做,它会工作
int temp=NewMethod(minValue, maxValue, random);
int x = numbers.Where(v => v == temp).First();
我添加了lastNumber字段以帮助调试代码,当它崩溃时你可以看到该值存在于集合中
PS
问题不是随机变量,我删除了参数并在方法内部创建了一个新的局部随机但问题仍然存在
更新
事实证明,您不需要循环来使其崩溃。 如果您多次运行该程序,您将再次收到错误
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
class Program
{
static int lastNumber;
static void Main()
{
int minValue = 1, maxValue = 100000;
var numbers = Enumerable.Range(minValue, maxValue).ToArray();
//Crashes sometimes
int x = numbers.Where(v => v == NewMethod(minValue, maxValue)).First();
Console.WriteLine("Finished");
Console.ReadLine();
}
private static int NewMethod(int minValue, int maxValue)
{
Random random = new Random();
var a1 = random.Next(minValue + 1, maxValue - 1);
lastNumber = a1;
return a1;
}
}
【问题讨论】:
-
据我所知,您不能在 lamda 表达式中使用“复杂”方法,只能使用可以转换为语句的东西。 stackoverflow.com/questions/1883920/…
-
@ZivWeissman 您可以调用“复杂”方法 - 该问题是关于具有副作用的方法。