随机排序的 IEnumerable 每次使用时都会更改顺序,而不是重新排序一次

Randomly ordered IEnumerable changes order each time it is used, instead of being reordered once

我正在使用 OrderBy 和 Random() 洗牌 IEnumerable,然后使用 ElementAt 选择其中的一些。

简化版:

var r = new Random(DateTime.Now.Millisecond);
IEnumerable<IPublishedContent> testimonialsShuffled = testimonials.OrderBy(x => r.Next());

var testimonialA = testimonialsShuffled.ElementAt(0);
var testimonialB = testimonialsShuffled.ElementAt(1);
var testimonialC = testimonialsShuffled.ElementAt(2);

事实证明,这并不总是像我预期的那样 return 三个不同的元素,因为每次使用 testimonialsShuffled 时,它似乎都会重新排序。

var testimonialA = testimonialsShuffled.ElementAt(0);
var testimonialB = testimonialsShuffled.ElementAt(0);
var testimonialC = testimonialsShuffled.ElementAt(0);

同样,我希望这段代码产生三个相等的变量,但它们通常不同(因为 testimonialsShuffled 中的第一个元素每次都会改变)。

我的目标只是对我的 IEnumerable 随机排序一次(这样它的顺序会在不同的页面加载时发生变化,但不会在单个视图中发生多次)。我做错了什么?

OrderBy 导致 IEnumerable,每次访问时都会重新计算(简单地说)。
要获得一个固定的结果,您必须将其“强制”到列表中。

var r = new Random(DateTime.Now.Millisecond);
var testimonialsShuffled = testimonials.OrderBy(x => r.Next()).ToList();

var testimonialA = testimonialsShuffled.ElementAt(0);
var testimonialB = testimonialsShuffled.ElementAt(1);
var testimonialC = testimonialsShuffled.ElementAt(2);

应该可以解决问题。