Click here to Skip to main content
15,565,403 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 11 Oct 2011

Tagged as

Stats

13.8K views
1 bookmarked

Let's randomize IEnumerable

Rate me:
Please Sign up or sign in to vote.
3.48/5 (7 votes)
12 Oct 2011CPOL
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 9:39
Qwertie12-Oct-11 9:39 
GeneralRe: Updated :) It is essentially now what cechode put forth, bu... Pin
Andrew Rissing12-Oct-11 10:00
Andrew Rissing12-Oct-11 10:00 
GeneralRe: Sometimes I feel that being a programmer is much like being ... Pin
Kabwla.Phone13-Oct-11 23:54
Kabwla.Phone13-Oct-11 23:54 
GeneralReason for my vote of 5 As promissed, a better vote! Pin
Kabwla.Phone12-Oct-11 4:54
Kabwla.Phone12-Oct-11 4:54 
GeneralRe: ;-) Pin
Andrew Rissing12-Oct-11 5:01
Andrew Rissing12-Oct-11 5:01 
GeneralReason for my vote of 5 Useful, i think about the same idea. Pin
Ubloobok12-Oct-11 2:23
Ubloobok12-Oct-11 2:23 
GeneralReason for my vote of 3 Can you do a performance test to see... Pin
Kabwla.Phone11-Oct-11 23:04
Kabwla.Phone11-Oct-11 23:04 
GeneralRe: There is no need to run performance testing against the two.... Pin
Andrew Rissing12-Oct-11 4:47
Andrew Rissing12-Oct-11 4:47 
GeneralRe: Sorry, initially read your comment as referring to Cechode's... Pin
Andrew Rissing12-Oct-11 4:53
Andrew Rissing12-Oct-11 4:53 
GeneralReason for my vote of 5 i like it better than mine Pin
cechode11-Oct-11 6:04
cechode11-Oct-11 6: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.