stainless.blog

Select a random item from a List


André da Silva Carrilho

Hi,

Created an extension method to get a random item from a List:

/// <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();