Best way to randomize an array with .NET

后端 未结 17 1122
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 01:55

What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I\'d like to create a new Array with the same strings b

17条回答
  •  一整个雨季
    2020-11-22 02:41

    You can also make an extention method out of Matt Howells. Example.

       namespace System
        {
            public static class MSSystemExtenstions
            {
                private static Random rng = new Random();
                public static void Shuffle(this T[] array)
                {
                    rng = new Random();
                    int n = array.Length;
                    while (n > 1)
                    {
                        int k = rng.Next(n);
                        n--;
                        T temp = array[n];
                        array[n] = array[k];
                        array[k] = temp;
                    }
                }
            }
        }
    

    Then you can just use it like:

            string[] names = new string[] {
                    "Aaron Moline1", 
                    "Aaron Moline2", 
                    "Aaron Moline3", 
                    "Aaron Moline4", 
                    "Aaron Moline5", 
                    "Aaron Moline6", 
                    "Aaron Moline7", 
                    "Aaron Moline8", 
                    "Aaron Moline9", 
                };
            names.Shuffle();
    

提交回复
热议问题