Click here to Skip to main content
15,891,906 members
Articles / Programming Languages / C#

Adding Random Functionality to Generic Lists using Extension Methods

Rate me:
Please Sign up or sign in to vote.
3.40/5 (3 votes)
29 Apr 2009CPOL2 min read 24.6K   170   7  
Extends IList to include a shuffle method and a 'select an element at random' method.
namespace DevWilson
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Adds extension methods for System.Collections.Generic.IList&lt;T&gt;.
    /// </summary>
    public static class IListRandomExtensions
    {
        private static Random random = new Random();

        /// <summary>
        /// Randomly shuffles the elements within the list.
        /// </summary>
        /// <typeparam name="T">The type of elements in the list.</typeparam>
        /// <param name="list">Represents a collection of objects that can be individually accessed by index.</param>
        public static void Shuffle<T>(this IList<T> list)
        {
            if (list.Count <= 1)
            {
                return; // nothing to do
            }

            // don't shuffle the last element with itself
            for (int i = 0; i < list.Count - 1; i++)
            {
                T x = list[i];

                int index = random.Next(i + 1, list.Count);
                list[i] = list[index];
                list[index] = x;
            }
        }

        /// <summary>
        /// Returns a single element from the list, selected at random.
        /// </summary>
        /// <typeparam name="T">The type of elements in the list.</typeparam>
        /// <param name="list">Represents a collection of objects that can be individually accessed by index.</param>
        /// <returns>An element from the list or the default value if no elements exist.</returns>
        public static T GetRandom<T>(this IList<T> list)
        {
            if (list.Count == 0)
            {
                return default(T);
            }

            return list[random.Next(0, list.Count)];
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Play.com
United Kingdom United Kingdom
Hi, my name's Andy Wilson and I live in Cambridge, UK where I work as a Senior C# Software Developer.

Comments and Discussions