RandomElements

public static IEnumerable<T> RandomElements<T>(this IEnumerable<T> collection, int count = 0)
{
    if (count > collection.Count() || count<=0) 
        count = collection.Count();
            
    List<int> usedIndices = new List<int>();
    Random random = new Random((int)DateTime.Now.Ticks);
    while (count > 0)
    {
        int index = random.Next(collection.Count());
        if (!usedIndices.Contains(index))
        {
            yield return collection.ElementAt(index);
            usedIndices.Add(index);
            count--;
        }
    }            
}
Example:
//Get 4 random elements
IEnumerable<int> seq = Enumerable.Range(1, 50);
seq.RandomElements(4).ToList().ForEach(Console.WriteLine);

// randomize all (note: is slow on large collection!)
IEnumerable<int> seq2 = Enumerable.Range(1, 50);
seq2.RandomElements().ToList().ForEach(Console.WriteLine);

Description

Returns a number of random elements from a collection

Details

Double click on the code to select all.

 

;