Best way to randomize an array with .NET

后端 未结 17 1126
隐瞒了意图╮
隐瞒了意图╮ 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:45

    This is a complete working Console solution based on the example provided in here:

    class Program
    {
        static string[] words1 = new string[] { "brown", "jumped", "the", "fox", "quick" };
    
        static void Main()
        {
            var result = Shuffle(words1);
            foreach (var i in result)
            {
                Console.Write(i + " ");
            }
            Console.ReadKey();
        }
    
       static string[] Shuffle(string[] wordArray) {
            Random random = new Random();
            for (int i = wordArray.Length - 1; i > 0; i--)
            {
                int swapIndex = random.Next(i + 1);
                string temp = wordArray[i];
                wordArray[i] = wordArray[swapIndex];
                wordArray[swapIndex] = temp;
            }
            return wordArray;
        }         
    }
    

提交回复
热议问题