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