Best way to randomize an array with .NET

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

    If you're on .NET 3.5, you can use the following IEnumerable coolness:

    Random rnd=new Random();
    string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();    
    

    Edit: and here's the corresponding VB.NET code:

    Dim rnd As New System.Random
    Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()
    

    Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like lock (MyRandomArray) anyway in order not to corrupt your data, which will protect rnd as well.

    Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the MSDN documentation, you should use something derived from System.Security.Cryptography.RandomNumberGenerator if you're doing anything security-related. For example:

    using System.Security.Cryptography;
    

    ...

    RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
    string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
    

    ...

    static int GetNextInt32(RNGCryptoServiceProvider rnd)
        {
            byte[] randomInt = new byte[4];
            rnd.GetBytes(randomInt);
            return Convert.ToInt32(randomInt[0]);
        }
    

提交回复
热议问题