Created
September 14, 2016 04:14
-
-
Save ddikman/64ce2fcaae609ce3a8168037c7fec41b to your computer and use it in GitHub Desktop.
Extension methods for sampling items in generic collections.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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