Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created December 8, 2010 20:45
Show Gist options
  • Save chrisnicola/733892 to your computer and use it in GitHub Desktop.
Save chrisnicola/733892 to your computer and use it in GitHub Desktop.
//Apply selector to a random subset of source of size count and return the results
public static class ExtensionHelpers {
public static IEnumerable<TOut> SelectRandom<TSource, TOut>(this IEnumerable<TSource> source,
Func<TSource, TOut> selector,
int count) {
var rand = new Random((int) (DateTime.Now.Ticks % int.MaxValue));
for (var i = 0; i < count; i++)
yield return selector(source.ElementAt(rand.Next(source.Count())));
}
}
//Basic examples
var randomNames = listOfPeople.SelectRandom(person => person.Name, 10);
var randomData = listOfIds.SelectRandom(id => data.GetDataForId(id), 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment