Beispiel #1
0
        public static IList <T> ShuffleCryptographically <T>(this IList <T> list, RandomNumberGenerator randomNumberGenerator = null, bool doNotDispose = false)
        {
            try
            {
                if (list is null)
                {
                    throw new ArgumentNullException(nameof(list));
                }

                if (randomNumberGenerator == null)
                {
                    randomNumberGenerator = RandomNumberGenerator.Create();
                }

                using (var random = new CryptoRandom(randomNumberGenerator, doNotDispose))
                {
                    return(ShuffleInternally(list, (min, max) =>
                    {
                        int i;

                        do
                        {
                            random.TryNext <int>(out i);

                            if (i == int.MaxValue)
                            {
                                i = 0;
                            }

                            i = Math.Abs(i);
                        } while (i == int.MaxValue);

                        int diff = max - min;
                        int part = int.MaxValue / diff;
                        int value = i / part;
                        return value + min;
                    }));
                }
            }
            finally
            {
                if (!doNotDispose)
                {
                    randomNumberGenerator?.Dispose();
                }
            }
        }