Quantcast
Channel: User Rei Miyasaka - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Answer by Rei Miyasaka for Linq Orderby random ThreadSafe for use in ASP.NET

$
0
0

Probably best to write your own extension method to do it.

public static class Extensions{    static readonly Random random = new Random();    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)    {        return Shuffle(items, random);    }    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items, Random random)    {        // Un-optimized algorithm taken from        // http://en.wikipedia.org/wiki/Knuth_shuffle#The_modern_algorithm        List<T> list = new List<T>(items);        for (int i = list.Count - 1; i >= 1; i--)         {            int j = random.Next(0, i);            T temp = list[i];            list[i] = list[j];            list[j] = temp;        }        return list;    }}

Viewing all articles
Browse latest Browse all 45

Trending Articles