I am trying to create a method where it will allow me to take X amount of random elements from a collection, I have coded one to get 1 random element, but I need to make the "amount" parameter matter, how can I make it take that into account?
I also need to add a Where, because I only need to grab elements where the class instance inside the collection (HashSet) has a public field called 'Enabled' and is equal to true.
private static readonly Random Random = new Random();
private static readonly object Sync = new object();
public static T RandomElement<T>(this IEnumerable<T> enumerable, int amount)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
var count = enumerable.Count();
int ndx;
lock (Sync)
ndx = Random.Next(count); // returns non-negative number less than max
return enumerable.ElementAt(ndx);
}