Click here to Skip to main content
15,867,949 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Let's randomize IEnumerable

Rate me:
Please Sign up or sign in to vote.
3.48/5 (7 votes)
12 Oct 2011CPOL 15.3K   1   10
I was actually going to suggest a simpler version of cechode's version, but along the same lines.public static IEnumerable Randomize(this IEnumerable source){ Random r = new Random(); return source.Select(x => new { Key = r.Next(), Value = x }) .OrderBy(x => x.Key) ...
I was actually going to suggest a simpler version of cechode's version, but along the same lines.
C#
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
  Random r = new Random();

  return source.Select(x => new { Key = r.Next(), Value = x })
   .OrderBy(x => x.Key)
   .Select(x => x.Value);
}


Edit: In response to http://blogs.msdn.com/b/ericlippert/archive/2011/01/31/spot-the-defect-bad-comparisons-part-four.aspx[^], I've updated it to generate a single random number to sort upon.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.

So..If you're not moving forward, you're moving backwards.

Comments and Discussions

 
GeneralReason for my vote of 1 Random numbers should never be fed i... Pin
Qwertie12-Oct-11 8:39
Qwertie12-Oct-11 8:39 
GeneralRe: Updated :) It is essentially now what cechode put forth, bu... Pin
Andrew Rissing12-Oct-11 9:00
Andrew Rissing12-Oct-11 9:00 
GeneralRe: Sometimes I feel that being a programmer is much like being ... Pin
Kabwla.Phone13-Oct-11 22:54
Kabwla.Phone13-Oct-11 22:54 
GeneralReason for my vote of 5 As promissed, a better vote! Pin
Kabwla.Phone12-Oct-11 3:54
Kabwla.Phone12-Oct-11 3:54 
GeneralRe: ;-) Pin
Andrew Rissing12-Oct-11 4:01
Andrew Rissing12-Oct-11 4:01 
GeneralReason for my vote of 5 Useful, i think about the same idea. Pin
Ubloobok12-Oct-11 1:23
Ubloobok12-Oct-11 1:23 
GeneralReason for my vote of 3 Can you do a performance test to see... Pin
Kabwla.Phone11-Oct-11 22:04
Kabwla.Phone11-Oct-11 22:04 
GeneralRe: There is no need to run performance testing against the two.... Pin
Andrew Rissing12-Oct-11 3:47
Andrew Rissing12-Oct-11 3:47 
GeneralRe: Sorry, initially read your comment as referring to Cechode's... Pin
Andrew Rissing12-Oct-11 3:53
Andrew Rissing12-Oct-11 3:53 
GeneralReason for my vote of 5 i like it better than mine Pin
cechode11-Oct-11 5:04
cechode11-Oct-11 5:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.