Web Developer, Software Engineer and Mixed Language Artist
RSS icon Email icon Home icon
  • Get random item from IList< T >

    Posted on November 3rd, 2010 Jamie No comments

    In what could turn out to be a series of posts about helpful extension methods I thought I’d include this quick little method for getting a random item from an IList collection.

    ?View Code CSHARP
    public static T GetRandomItem<T>(this IList<T> collection)
            {
                return collection[(new Random().Next(0, collection.Count))];
            }

    This can then be used as follows:

    ?View Code CSHARP
    var collectionList = new List<string> {"String 1", "String 2", "String 3"};
    string item = collectionList.GetRandomItem();

    Leave a reply