ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Randomize

OrderBy() is nice when you want a consistent & predictable ordering. This method is NOT THAT! Randomize() - Use this extension method when you want a different or random order every time! Useful when ordering a list of things for display to give each a fair chance of landing at the top or bottom on each hit. {customers, support techs, or even use as a randomizer for your lottery ;) }

Source

public static class IEnumerableExtensions
{
         
    public static IEnumerable<t> Randomize<t>(this IEnumerable<t> target)
    {
        Random r = new Random();
           
        return target.OrderBy(x=>(r.Next()));
    }        
}

Example

// use this on any collection that implements IEnumerable!
// List, Array, HashSet, Collection, etc

List<string> myList = new List<string> { "hello", "random", "world", "foo", "bar", "bat", "baz" };

foreach (string s in myList.Randomize())
{
    Console.WriteLine(s);
}

Author: Phil Campbell

Submitted on: 2 nov. 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 13336