Ai đó có thể giải thích cho tôi tại sao truy vấn LINQ sau đây ném một InvalidOperationException?
(Đừng nói rằng danh sách này không có các yếu tố, giá trị mà tôi đang tìm kiếm luôn luôn tồn tại trong bộ sưu tập)Trình tự không chứa các phần tử
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;
}
}
Vấn đề chỉ xuất hiện khi tôi gọi NewMethod bên expession lambda tôi.
Nếu làm được điều này nó hoạt động
int temp=NewMethod(minValue, maxValue, random);
int x = numbers.Where(v => v == temp).First();
tôi thêm lĩnh vực lastNumber để giúp gỡ lỗi mã, bạn có thể thấy rằng giá trị tồn tại trong bộ sưu tập khi nó bị treo
PS
Vấn đề không phải là biến ngẫu nhiên, tôi loại bỏ các tham số và tạo ra một mới địa phương ngẫu nhiên trong phương pháp này nhưng vấn đề vẫn còn tồn tại
cập nhật
hóa ra rằng bạn không cần vòng lặp để làm cho nó sụp đổ. Nếu bạn chạy chương trình nhiều lần, bạn sẽ nhận được lỗi một lần nữa
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;
}
}
Theo tôi biết bạn không thể sử dụng một phương thức "phức tạp" bên trong biểu thức lamda, chỉ những thứ có thể được chuyển đổi thành câu lệnh. http://stackoverflow.com/questions/1883920/call-a-function-for-each-value-in-a-generic-c-sharp-collection –
@ZivWeissman Bạn có thể gọi các phương thức "phức tạp" - câu hỏi đó là nói về phương pháp _with tác dụng phụ_. –