I was looking the same thing, I didn't find it (sorry if it's published somewhere else), so I came up with this...
Example enum:
[Flags]
public enum DayOfWeek
{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
};
Extension:
static class EnumerationExtension
{
private static System.Random R { get; set; } = new System.Random();
public static Enum Random(this Enum enumeration)
{
var type = enumeration.GetType();
var strs = enumeration.ToString().Split(", ");
var index = R.Next(strs.Length);
return (Enum)Enum.Parse(type, strs[index]);
}
}
Usage, let's pick Monday, Wednesday and Friday:
var mwf = DayOfWeek.Monday | DayOfWeek.Wednesday | DayOfWeek.Friday;
Console.WriteLine($"Chosen days: {mwf}");
for (int i = 0; i < 10; ++i)
Console.WriteLine($"Random day: {mwf.Random()}");
Output, as you can see it only picks 1 of the 3 previous days:
Chosen days: Monday, Wednesday, Friday
Random day: Friday
Random day: Wednesday
Random day: Monday
Random day: Wednesday
Random day: Monday
Random day: Monday
Random day: Wednesday
Random day: Friday
Random day: Monday
Random day: Monday
I leave the fiddle to test
It's nothing fancy, but I hope to help people like me that are not "seniors" in C#