RandomElements
Returns a number of random elements from a collection
Source
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);
Author: Timmy Kokke
Submitted on: 9 mrt. 2011
Language: C#
Type: System.Collections.Generic.IEnumerable<T>
Views: 4964