为什么LINQ不确定?

Evo*_*lor 0 c# linq ienumerable non-deterministic deferred-execution

我随机排序了一个IEnumerable.我继续打印出相同的元素,并获得不同的结果.

string[] collection = {"Zero", "One", "Two", "Three", "Four"};
var random = new Random();
var enumerableCollection = collection.OrderBy(e => random.NextDouble());

Console.WriteLine(enumerableCollection.ElementAt(0));
Console.WriteLine(enumerableCollection.ElementAt(0));
Console.WriteLine(enumerableCollection.ElementAt(0));
Console.WriteLine(enumerableCollection.ElementAt(0));
Console.WriteLine(enumerableCollection.ElementAt(0));
Run Code Online (Sandbox Code Playgroud)

每次写入都会给出不同的随机元素.为什么订单没有保留?

在.NET Fiddle上看到它

Ric*_*imo 5

Linq推迟执行,直到绝对必要.你可以认为enumerableCollection是定义如何你想枚举的工作,而不是结果一个枚举.

因此,每当你枚举它(你打电话时正在进行ElementAt)时,它将重新枚举你的原始集合,并且由于你选择随机订购,每次答案都是不同的.

你可以通过.ToList()在最后添加它来做它你期望的事情:

var enumerableCollection = collection.OrderBy(e => random.NextDouble()).ToList();
Run Code Online (Sandbox Code Playgroud)

这将执行枚举,并将结果存储在List中.通过使用它,每次枚举时都不会重新枚举原始列表enumerableCollection.