I have a List
I would like to re-order it so so they are in random order.
What's the quickest way to do this (by quickest, I mean least amount of code)
Note: as per mquander's comment, the following answer is not the recommended way to perform "random ordering" since it's semantically incorrect, is not efficient compared to the accepted shuffle algorithm, it's based on the private implementation details of
Guid
s, and even abuses LINQ query syntax. However, it is the "least amount of code" (in terms of written by oneself as opposed to handled by the framework) as requested by the OP.
var randomOrdering = yourList.OrderBy(o => Guid.NewGuid());
If you want to randomly re-order in place you should shuffle the list, usage with an extension method is then a simple one-liner. This assumes you already have an IList
based collection.
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 a List<T>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With