Shuffle-List with LINQ

Programming C#

Let's say you have a List<T> and want to order that list by random.  Quite easy with the following extension method:

    static class ShuffleListExtension
{
private static Random rng = new Random();

public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}

Everytime you call .Shuffle() the list will be again randomly reordered.

   result = DbEntity.Where(...).ToList().Shuffle();
result = result.Shuffle(); // re-order the list a 2nd time