Shuffles an array of objects. - CSharp System

CSharp examples for System:Array Shuffle

Description

Shuffles an array of objects.

Demo Code

//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
using System.Linq;
using System.Collections.Generic;
using System;// w  w w. ja  va  2s. c  o m

public class Main{
        /// <summary>
        /// Shuffles an array of objects.
        /// </summary>
        /// <typeparam name="T">The type of the array to sort.</typeparam>
        /// <param name="array">The array to sort.</param>
        public static void Shuffle<T>(this T[] array)
        {
            var length = array.Length;
            var random = new Random();

            while (length > 1)
            {
                int randomNumber = random.Next(length--);
                T obj = array[length];
                array[length] = array[randomNumber];
                array[randomNumber] = obj;
            }
        }
}

Related Tutorials