Random Shuffle IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Random Shuffle IEnumerable

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;//from  w  w w  .  j  a v  a 2 s .  c o m

public class Main{
        public static T[] RandomShuffle<T>(this IEnumerable<T> source, Random random)
        {
            var sourceArray = source.ToArray();
            for (var i = 1; i < sourceArray.Length; i++)
            {
                var swapIndex = random.Next(i - 1);
                var temp = sourceArray[swapIndex];
                sourceArray[swapIndex] = sourceArray[i];
                sourceArray[i] = temp;
            }
            return sourceArray;
        }
}

Related Tutorials