24

I need to rearrange my List array, it has a non-determinable number of elements in it.

Can somebody give me example of how i do this, thanks

brux
  • 3,197
  • 10
  • 44
  • 78

2 Answers2

68
List<Foo> source = ...
var rnd = new Random();
var result = source.OrderBy(item => rnd.Next());

Obviously if you want real randomness instead of pseudo-random number generator you could use RNGCryptoServiceProvider instead of Random.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 8
    No.. this is a bad idea, read this: http://blogs.msdn.com/b/ericlippert/archive/2011/01/31/spot-the-defect-bad-comparisons-part-four.aspx – chillitom Mar 21 '11 at 20:51
  • 1
    Is there a real randmoness? I thought it is impossible. – Sanjeevakumar Hiremath Mar 21 '11 at 20:53
  • @Sanjeevakumar Hiremath, no there is no real randomness indeed. But with RNGCryptoServiceProvider at least the randomness should be sufficient :-) – Darin Dimitrov Mar 21 '11 at 20:54
  • 7
    @chillitom, no this doesn't have the problem in that article. In Eric's article, the randomness is poorly seeded, and also the comparison is breaking the total ordering requirement of comparison methods. In Darin's example here, each item is assigned a random number once, and then ordered according to it. I think kprobst's solution is still better (well-known efficient shuffling algorithm), but Darin's is correct too. – Jon Hanna Mar 21 '11 at 21:36
  • 1
    Bad idea, see comments [here](http://stackoverflow.com/a/3456788/207655). – o0'. Oct 10 '13 at 08:38
  • 1
    Doesnt seem to work. Always get a list in the same order? :( – Piotr Kula Jan 05 '14 at 15:37
  • same as @ppumkin here. – Veverke Feb 23 '15 at 16:13
  • @ppumpkin @Veverke This doesn't work as-is, because `rnd` is set to `new Random()` each time (i.e. with the same seed). Basically, set `rnd` at the beginning of your program and then never assign to it again (make it `static` or something). Then, the only line you actually need at shuffle-time is the first and the third. – Joshua Grosso Reinstate CMs Jun 27 '16 at 23:12
  • @ BalinKingOfMoria: thanks, but I must have tried it like you say, since I am used to Random and know that I need to give it a seed and use the same instance. I do not remember what I tried then, ... sounds strange I tried it as it is. Thanks, anyway. – Veverke Jun 28 '16 at 08:13
  • _I am used to Random and know that I need to give it a seed_ yes, give it a seed to create always the same sequence. don't give it a seed to create uniques sequences. – TaW Feb 28 '17 at 16:04
  • What is `item` in this example? Please forgive noobness. – tolache Sep 28 '19 at 08:30
21

This is an extension method that will shuffle a List<T>:

    public static void Shuffle<T>(this IList<T> list) {
        int n = list.Count;
        Random rnd = new Random();
        while (n > 1) {
            int k = (rnd.Next(0, n) % n);
            n--;
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
kprobst
  • 16,165
  • 5
  • 32
  • 53
  • +1 I've not tested this in my code (i.e. not sure if it works), but I like it so far! Does every element get shuffled, or is that not necessary? –  Mar 21 '11 at 20:55
  • The whole list is shuffled, yes. Note that for larger lists you might want to integrate a more random random generator (Darin's answer below) into the solution. I use it for smaller sets (say ~300 tops) and it works well enough. – kprobst Mar 21 '11 at 20:58
  • 1
    You can just say `int k = rnd.Next(0, n)`. The `%` is unnecessary since the dividend is always less than `n`. – Kevin Mar 21 '11 at 21:05
  • 1
    Looks like a sound Fisher-Yates implementation, which is what I was going to offer. – Jon Hanna Mar 21 '11 at 21:23
  • 13
    There is a problem with this implementation! Initializing a new `Random` on each call will yield predictable shuffling results. Instead, place `private static readonly Random rnd = new Random();` into the static class this method sits in. Finally, it would have been nice if you had given [your source for this answer](http://stackoverflow.com/revisions/1262619/1) credit, because then the flaw in your own post might have been discovered sooner before people went off and used it without any hint it needed fixing. – ErikE Sep 11 '15 at 17:08
  • 1
    https://stackoverflow.com/questions/273313/randomize-a-listt – nishantvodoo May 22 '17 at 17:19