LINQ style Sample method 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 &gt; li").Sample(3);

Here's the how I implemented it:

I welcome any feedback or optimizations!

    /// &lt;summary&gt;
    ///  returns a random sample of the elements in an IEnumerable
    /// &lt;/summary&gt;
    public static IEnumerable&lt;T&gt; Sample&lt;T&gt;(this IEnumerable&lt;T&gt; population, int sampleSize)
    {
        List&lt;T&gt; localPopulation = population.ToList();
        if (localPopulation.Count() &lt; sample.size) return localPopulation;

        List&lt;T&gt; sample = new List&lt;T&gt;(sampleSize);

        Random random = new Random();
        while(sample.Count &lt; sampleSize)
        {
            int i = random.Next(0, localPopulation.Count);
            sample.Add(localPopulation[i]);
            localPopulation.RemoveAt(i);
        }

        return sample;
    }
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:

/// &lt;summary&gt;
///  random number generator for the enumerable sampler.
/// &lt;/summary&gt;
private static readonly Random random = new Random();

/// &lt;summary&gt;
///  returns a random sample of the elements in an IEnumerable
/// &lt;/summary&gt;
public static IEnumerable&lt;T&gt; Sample&lt;T&gt;(this IEnumerable&lt;T&gt; population, int sampleSize)
{
    if (population == null)
    {
        return null;
    }

    List&lt;T&gt; localPopulation = population.ToList();
    if (localPopulation.Count &lt; sample.size) return localPopulation;

    List&lt;T&gt; sample = new List&lt;T&gt;(sampleSize);

    while(sample.Count &lt; sampleSize)
    {
        int i = random.Next(0, localPopulation.Count);
        sample.Add(localPopulation[i]);
        localPopulation.RemoveAt(i);
    }

    return sample;
}