开发者

shuffle (rearrange randomly) a List<string> [duplicate]

This question already has answers here: 开发者_如何学C Randomize a List<T> (28 answers) Closed 10 years ago.

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


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.


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;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜