Click here to Skip to main content
13,044,115 members (108,859 online)
Click here to Skip to main content

Stats

18.5K views
7 bookmarked
Posted 28 Apr 2009

Adding Random Functionality to Generic Lists using Extension Methods

, 29 Apr 2009
Extends IList to include a shuffle method and a 'select an element at random' method.
namespace IListRandomExtensionsSample
{
    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
            }

            for (int i = 0; i < list.Count; i++)
            {
                int newIndex = random.Next(0, list.Count);
                
                // swap the two elements over
                T x = list[i];
                list[i] = list[newIndex];
                list[newIndex] = 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)

Share

About the Author

andywilsonuk
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.

You may also be interested in...

Pro
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 29 Apr 2009
Article Copyright 2009 by andywilsonuk
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid