Best way to randomize an array with .NET

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

    Ok, this is clearly a bump from my side (apologizes...), but I often use a quite general and cryptographically strong method.

    public static class EnumerableExtensions
    {
        static readonly RNGCryptoServiceProvider RngCryptoServiceProvider = new RNGCryptoServiceProvider();
        public static IEnumerable Shuffle(this IEnumerable enumerable)
        {
            var randomIntegerBuffer = new byte[4];
            Func rand = () =>
                                 {
                                     RngCryptoServiceProvider.GetBytes(randomIntegerBuffer);
                                     return BitConverter.ToInt32(randomIntegerBuffer, 0);
                                 };
            return from item in enumerable
                   let rec = new {item, rnd = rand()}
                   orderby rec.rnd
                   select rec.item;
        }
    }
    

    Shuffle() is an extension on any IEnumerable so getting, say, numbers from 0 to 1000 in random order in a list can be done with

    Enumerable.Range(0,1000).Shuffle().ToList()
    

    This method also wont give any surprises when it comes to sorting, since the sort value is generated and remembered exactly once per element in the sequence.

提交回复
热议问题