If I understand correctly, the question arises of returning a random enumeration value from a flag enumeration value, rather than returning a random element from a flag enumeration.
[Flags]
private enum Shot
{
Whisky = 1,
Absynthe = 2,
Pochin = 4,
BrainEraser = Whisky | Absynthe | Pochin
}
[Test]
public void Test()
{
Shot myCocktail = Shot.Absynthe | Shot.Whisky;
Shot randomShotInCocktail = GetRandomShotFromCocktail(myCocktail);
}
private static Shot GetRandomShotFromCocktail(Shot cocktail)
{
Random random = new Random();
Shot[] cocktailShots = Enum.GetValues(typeof(Shot)).
Cast<Shot>().
Where(x => cocktail.HasFlag(x)).ToArray();
Shot randomShot = cocktailShots[random.Next(0, cocktailShots.Length)];
return randomShot;
}
Edit
And, obviously, you should check that the enum is a valid value, for example:
Shot myCocktail = (Shot)666;
Edit
Simplified
source
share