shuffle (rearrange randomly) a List [dupli

2019-01-14 11:46发布

This question already has an answer here:

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

2条回答
爷的心禁止访问
2楼-- · 2019-01-14 12:00
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.

查看更多
We Are One
3楼-- · 2019-01-14 12:15

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;
        }
    }
查看更多
登录 后发表回答