Shuffle elements of list in random order. To get a random on the order used Random class - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Shuffle elements of list in random order. To get a random on the order used Random class

Demo Code


using System.Security.Cryptography;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w  ww  .  ja v a2s.  co m*/

public class Main{
        /// <summary>
        /// Shuffle elements of list in random order. To get a random on the order used Random class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public static void FastShuffleThis<T>(this IList<T> list)
        {
            var rng = new Random();
            var n = list.Count;
            while (n > 1)
            {
                n--;
                var k = rng.Next(n + 1);
                var value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
}

Related Tutorials