Created
September 21, 2021 16:26
-
-
Save profexorgeek/9a5c897a62829741d979347869d54f0d to your computer and use it in GitHub Desktop.
Two extension methods that make it really easy to grab a random element from a list. You will need to update `RandomService.Random` with a global RNG.
This file contains hidden or 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
public static class CollectionExtensions | |
{ | |
/// <summary> | |
/// A Linq-like method for getting a random element from an IEnumerable | |
/// </summary> | |
/// <typeparam name="T">The element type</typeparam> | |
/// <param name="array">The array to fetch an element from</param> | |
/// <param name="rand">Optional Random instance, if not provided | |
/// the method will use the RandomService.</param> | |
/// <returns>An element of type T or default(T)</returns> | |
public static T Random<T>(this IEnumerable<T> enumerable, Random rand = null) | |
{ | |
rand = rand ?? RandomService.Random; | |
T o; | |
var c = enumerable.Count(); | |
if (c > 0) | |
{ | |
o = enumerable.ElementAt(rand.Next(0, c)); | |
} | |
else | |
{ | |
o = default(T); | |
} | |
return o; | |
} | |
/// <summary> | |
/// A Linq-like method for getting a random element from an array | |
/// </summary> | |
/// <typeparam name="T">The element type</typeparam> | |
/// <param name="array">The array to fetch an element from</param> | |
/// <param name="rand">Optional Random instance, if not provided | |
/// the method will use a static default instance.</param> | |
/// <returns>An element of type T or default(T)</returns> | |
public static T Random<T>(this Array array, Random rand = null) | |
{ | |
rand = rand ?? RandomService.Random; | |
T o; | |
var c = array.Length; | |
if (c > 0) | |
{ | |
try | |
{ | |
o = (T)array.GetValue(rand.Next(0, c)); | |
} | |
catch | |
{ | |
o = default(T); | |
} | |
} | |
else | |
{ | |
o = default(T); | |
} | |
return o; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment