问题
I wonder why is the reason why this code never finishes its execution.
It makes use of MoreLinq
void Main()
{
var values = MoreEnumerable.Random(1, 200);
var filtered = MyMethod(values)
.Take(2)
.Dump();
}
public IEnumerable<int> MyMethod(IEnumerable<int> source)
{
return source
.Select(x => new[] { x })
.Aggregate((a, b) => new[] { a.Last() + b.First()});
}
回答1:
Because MoreEnumerable.Random(1, 200)
returns an infinite sequence and the .Aggregate
statement in MyMethod
is trying to enumerate the whole sequence.
If I understand correctly what you are trying to do, moving Take
to MyMethod
may work:
public static IEnumerable<int> MyMethod(IEnumerable<int> source)
{
return source
.Select(x => new[] { x })
.Take(2)
.Aggregate((a, b) => new[] { a.Last() + b.First() });
}
回答2:
I find out that this method(.Random(1, 200)) returns an infinite sequence of random integers using the standard .NET random number generator. Documentation
回答3:
MoreEnumerable.Random enumerate an infinite list of random integers, that's why.
You have to replace
var values = MoreEnumerable.Random(1, 200);
by a finite list:
var values = MoreEnumerable.Random(1, 200).Take(100);
For reason I do not know yet, the Aggregation seems to take the whole list, despite you put .Take(2) two lines after.
来源:https://stackoverflow.com/questions/66198483/why-does-it-hang-indefinitely