Skip to content

Instantly share code, notes, and snippets.

@ddikman
Created September 14, 2016 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddikman/64ce2fcaae609ce3a8168037c7fec41b to your computer and use it in GitHub Desktop.
Save ddikman/64ce2fcaae609ce3a8168037c7fec41b to your computer and use it in GitHub Desktop.
Extension methods for sampling items in generic collections.
using System;
using System.Collections.Generic;
using System.Linq;
namespace System.Collections.Generic
{
public static class SampleCollectionExtension
{
private static readonly Random Random = new Random();
public static TItemType Sample<TItemType>(this ICollection<TItemType> collection)
{
var index = Random.Next(0, collection.Count - 1);
return collection.ElementAt(index);
}
public static TItemType Sample<TItemType>(this TItemType[] collection)
{
var index = Random.Next(0, collection.Length - 1);
return collection[index];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment