Jamie Dixon
Web Developer, Software Engineer and Mixed Language Artist
-
Get random item from IList< T >
Posted on November 3rd, 2010 No commentsIn 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. public static T GetRandomItem<T>(this IList<T> collection) { return collection[(new Random().Next(0, collection.Count))]; }
This can then be used as follows:
var collectionList = new List<string> {"String 1", "String 2", "String 3"}; string item = collectionList.GetRandomItem();
Leave a reply


