CSharp examples for System.Collections.Generic:IEnumerable
Picks up random element from a specified sequence and returns it.
using System.Text; using System.Linq; using System.Collections.Generic; using System;// w w w. j a v a 2s. c o m public class Main{ /// <summary> /// <para>Picks up random element from a specified sequence and returns it.</para> /// </summary> /// <typeparam name="T">Type of elements in a sequence.</typeparam> /// <param name="self">Source sequence of elements.</param> /// <returns>Random member of <paramref name="self"/> sequence.</returns> /// <exception cref="ArgumentNullException">If <paramref name="self"/> is a <c>null</c> reference. If <paramref name="self"/> contains no elements, returns <c>null</c>.</exception> public static T Random<T>(this IEnumerable<T> self) { Assertion.NotNull(self); var max = self.Count(); return (T) (max > 0 ? self.ElementAt(new Random().Next(max)) : (object) null); } }