Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OrderBy results in an IEnumerable, which is re-evaluated every time you access it (simply put).
To get one fixed result, you have to "force" it into a list.

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);

should do the trick.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...