If I have a list of integers:
List myValues = new List(new int[] { 1, 2, 3, 4, 5, 6 } );
How would I get 3 random integer
One simple way:
Random r = new Random();
IEnumerable threeRandom = myValues.OrderBy(x => r.Next()).Take(3);
The better way: Fisher–Yates shuffle:
public static class EnumerableExtensions
{
public static IEnumerable Shuffle(this IEnumerable source)
{
return source.Shuffle(new Random());
}
public static IEnumerable Shuffle(this IEnumerable source, Random rng)
{
if (source == null) throw new ArgumentNullException("source");
if (rng == null) throw new ArgumentNullException("rng");
return source.ShuffleIterator(rng);
}
private static IEnumerable ShuffleIterator(
this IEnumerable source, Random rng)
{
List buffer = source.ToList();
for (int i = 0; i < buffer.Count; i++)
{
int j = rng.Next(i, buffer.Count);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
}
how you use it:
IEnumerable threeRandom = myValues.Shuffle().Take(3);