Best way to randomize an array with .NET

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

    Just thinking off the top of my head, you could do this:

    public string[] Randomize(string[] input)
    {
      List inputList = input.ToList();
      string[] output = new string[input.Length];
      Random randomizer = new Random();
      int i = 0;
    
      while (inputList.Count > 0)
      {
        int index = r.Next(inputList.Count);
        output[i++] = inputList[index];
        inputList.RemoveAt(index);
      }
    
      return (output);
    }
    

提交回复
热议问题