Best way to randomize an array with .NET

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

    You don't need complicated algorithms.

    Just one simple line:

    Random random = new Random();
    array.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();
    

    Note that we need to convert the Array to a List first, if you don't use List in the first place.

    Also, mind that this is not efficient for very large arrays! Otherwise it's clean & simple.

提交回复
热议问题