4

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)

Diskdrive
  • 18,107
  • 27
  • 101
  • 167
  • possible duplicate of [Randomize a List in C#](http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp) – nawfal Feb 12 '13 at 10:51

2 Answers2

11

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());
John Rasch
  • 62,489
  • 19
  • 106
  • 139
  • 6
    Neither nice nor elegant. If you want to "order by a random number," then generate random numbers, don't generate GUIDs. And if you want to shuffle a list, use a shuffling algorithm, don't "order by a random number." – mqp May 29 '11 at 01:44
  • 1
    mquander : I used the other solution which worked well but out of curiousity, why isn't this answer good? Does it take much more time to generate a GUID than it is to generate a random number? – Diskdrive May 29 '11 at 03:43
  • @mquander - updated answer to reflect why it's not the best solution, thanks. – John Rasch Dec 19 '11 at 18:16
  • 3
    out of curiosity - why not simply use data.OrderBy(o => rnd.Next());? – Arsen Zahray Feb 15 '12 at 21:56
5

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>

Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335