I am shuffling an IEnumerable using OrderBy and Random() and then selecting some of them using ElementAt.
Simplified version:
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);
It turns out that this does not always return three distinct elements as I expected, because every time testimonialsShuffled
is used, it seems to get reordered.
var testimonialA = testimonialsShuffled.ElementAt(0);
var testimonialB = testimonialsShuffled.ElementAt(0);
var testimonialC = testimonialsShuffled.ElementAt(0);
Similarly, I would expect this code to result in three equal variables, but instead they usually differ (as the first element in testimonialsShuffled changes each time).
My goal is just order my IEnumerable randomly once (so that its order changes on different page loads, but not multiple times in a single view). What am I doing wrong?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…