随机

/// 
/// An IEnumerable<T> extension method that picks a random item from the given
/// collection.
/// 
/// Generic type parameter.
/// The collection to act on. 
///  A T picked at random from the collection. 
public static T Random(this IEnumerable collection)
{
    if(collection == null) throw new ArgumentNullException("collection");
 
    if (!collection.Any())
    {
        return default(T);
    }
    
    var random = new Random();
    return collection.ElementAt(random.Next(collection.Count()));
}
var players = new List<Player>()
{
    new Player("Joseph"),
    new Player("Alice"),
    new Player("Maddox")
};
 
var player = players.Random();

 

posted on 2017-10-25 14:53  武胜-阿伟  阅读(206)  评论(0编辑  收藏  举报