Fastest way to randomly reorder a LINQ collection?

I have a list

I would like to reorder it so that they are in random order.

What is the fastest way to do this (the fastest, I mean the least amount of code)

+4
source share
2 answers

If you want to randomly change the order, you have to shuffle the list, using the extension method is a simple one-line. It is assumed that you already have a collection based on IList .

Usage: myList.Shuffle();

 public static void Shuffle<T>(this IList<T> list) { Random rng = new Random(); 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; } } 

Credit goes to this answer: Randomize list <T>

+5
source

Note: according to mquander's comment, the following answer is not the recommended way to do “random ordering”, since it is semantically incorrect, not efficient compared to the accepted shuffling algorithm, it is based on private details of Guid s implementation, and even abuses LINQ query syntax. However, this is the “least amount of code" (from the point of view written by itself, not processed by the framework), as requested by OP.

 var randomOrdering = yourList.OrderBy(o => Guid.NewGuid()); 
+9
source

All Articles