tags:

views:

92

answers:

3

Given an arbitrary enumeration in C#, how do I select a random value?

(I did not find this very basic question on SO. I'll post my answer in a minute as reference for anyone, but please feel free to post your own answer.)

A: 

Use Enum.GetValues to retrieve an array of all values. Then select a random array item.

static readonly Random _Random = new Random();

static T RandomEnumValue<T> ()
{
    return Enum
        .GetValues (typeof (T))
        .Cast<T> ()
        .OrderBy (x => _Random.Next())
        .FirstOrDefault ();
}

Test:

for (int i = 0; i < 10; i++) {
    var value = RandomEnumValue<System.DayOfWeek> ();
    Console.WriteLine (value.ToString ());
}

->

Tuesday
Saturday
Wednesday
Monday
Friday
Saturday
Saturday
Saturday
Friday
Wednesday
mafutrct
Oh come on! Using GUIDs to create randomness? Please let this be a joke answer. (Apart from that, using random with `OrderBy` is ill-defined and works by chance alone, so it shouldn’t be used even though this is a neat trick.)
Konrad Rudolph
Indeed, using GUIDs like this is a hack. It should be replaced by a sane algorithm.
mafutrct
Replaced it with a less twisted way to shuffle. Can obviously be improved to use Random to directly select an element in the array, just as in Darin's answer.
mafutrct
A: 

Call Enum.GetValues; this returns an array that represents all possible values for your enum. Pick a random item from this array. Cast that item back to the original enum type.

Tim Robinson
+7  A: 
Array values = Enum.GetValues(typeof(Bar));
Random random = new Random();
Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
Darin Dimitrov
Make sure you don't keep recreating `random` in a tight loop though - otherwise you'll keep getting the same value.
ChrisF