Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to randomly re-order a LINQ collection?

Tags:

c#

.net

linq

c#-4.0

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)

like image 654
Diskdrive Avatar asked Dec 04 '22 21:12

Diskdrive


2 Answers

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 Guids, 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());
like image 169
John Rasch Avatar answered Dec 08 '22 10:12

John Rasch


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>

like image 32
BrokenGlass Avatar answered Dec 08 '22 11:12

BrokenGlass