Random number of items from a Generic List extension method

Posted by Tim on June 13, 2010 in .NET Framework, C# |

Here is a code snippet  for returning N number of items from a generic list using a extension method.  This requires .NET 3.5.

public static class Extensions
    {
        /// <summary>
        /// method for returning N number of random items from a generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static IEnumerable<T> Randomize<T>(this List<T> list, int count)
        {
            List<T> randomList = new List<T>();
            Random random = new Random();

            while (list.Count > 0)
            {
                //get the next random number between 0 and
                //the list count
                int idx = random.Next(0, list.Count);

                //get that index
                randomList.Add(list[idx]);

                //remove that item so it cant be added again
                list.RemoveAt(idx);
            }

            //return the specified number of items
            return randomList.Take(count);
        }

        /// <summary>
        /// method for returning 1 item from the generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static T Randomize<T>(this List<T> list)
        {
            return Randomize(list, 1).FirstOrDefault();
        }
    }

used in code by calling the following: List<mytype> = myGenericList.Randomise(5) or mytype = myGenericList.Randomise();

Tags: ,

Leave a Reply

Copyright © 2008-2012 Codelab Blog All rights reserved.
Desk Mess Mirrored version 1.9.1 theme from BuyNowShop.com.