Select a random item from a List

Hi,

Ever wanted to select a random item from a List<T>? Well, this is an extension method that does just that

/// <summary>
/// Gets a random element from the list.
/// </summary>
/// <typeparam name="T">The list element type.</typeparam>
/// <param name="list">The actual list.</param>
/// <returns>An element from the list.</returns>
public static T Random<T>(this List<T> list)
{
    var r = new Random();
    return list[r.Next(0, list.Count)];
}

To use it:

var list = new List<string> { "first", "second", "third", "fourth" };
var random = list.Random();

Enjoy!

Leave a comment

Your comment