I Needed a method to randomly sample an IEnumerable collection without replacement. I'm using this for writing behavioral acceptance tests.For example, in the test code, I write:GetElements(#SearchResults > li).Sample(3);Here's the how I implemented it:I welcome any feedback or optimizations!    /// <summary>    ///  returns a random sample of the elements in an IEnumerable    /// </summary>    public static IEnumerable<T> Sample<T>(this IEnumerable<T> population, int sampleSize)    {        List<T> localPopulation = population.ToList();        if (localPopulation.Count() < sample.size) return localPopulation;        List<T> sample = new List<T>(sampleSize);        Random random = new Random();        while(sample.Count < sampleSize)        {            int i = random.Next(0, localPopulation.Count);            sample.Add(localPopulation[i]);            localPopulation.RemoveAt(i);        }        return sample;    }
LINQ style Sample method
c#;linq
Make the Random generator a class-level member so you're not generating a new one with the default seed each time. Also, check your population for null:/// <summary>///  random number generator for the enumerable sampler./// </summary>private static readonly Random random = new Random();/// <summary>///  returns a random sample of the elements in an IEnumerable/// </summary>public static IEnumerable<T> Sample<T>(this IEnumerable<T> population, int sampleSize){    if (population == null)    {        return null;    }    List<T> localPopulation = population.ToList();    if (localPopulation.Count < sample.size) return localPopulation;    List<T> sample = new List<T>(sampleSize);    while(sample.Count < sampleSize)    {        int i = random.Next(0, localPopulation.Count);        sample.Add(localPopulation[i]);        localPopulation.RemoveAt(i);    }    return sample;}