ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetRandomItem

Return's a random item from a IList<T>

Source

/// <summary>
        /// Sorteia randomicamente um item de um IList e o retorna
        /// </summary>
        /// <typeparam name="T">O tipo da Lista</typeparam>
        /// <param name="input">A lista a ser avaliada</param>
        public static T GetRandomItem<T>(this IList<T> input)
        {
            if (input != null)
            {
                if (input.Count == 1)
                    return input[0];

                int n = rand.Next(input.Count() + 1);

                return input[n];
            }
            return (T)input;
        }
}

Example

List<string> myList = new List<string>();

// Populate the List ...
myList.Add(Something);

myList.GetRandomItem();

Author: Ewerton Luis de Mattos

Submitted on: 13 nov. 2009

Language: C#

Type: System.Collections.Generic.IList<T>

Views: 5168