tags:

views:

143

answers:

4

Given a group of about 20 enums that I cannot modify.

Im looking for an elegant solution to generate a random enum from a specific sample (ie, 2, 7, 18)

I could put these into an arraylist, but thought I would ask if there is something else I could try.

+1  A: 

You can get all the values for a given enum type with:

var values = Enum.GetValues(typeof(MyEnum));
Richard
+2  A: 

If your values are all of the same type:

MyEnum[] values = { MyEnum.Value2, MyEnum.Value7, MyEnum.Value18 };
Random random = new Random();
MyEnum randomValue = values[random.Next(values.Length)];
Mark Byers
A: 

The simplest solution is to put those enums you want to choose from into an array or list of some kind and randomly pick from that.

If you just randomly pick from the the full definition you'll have to check the answer and reject those you don't want.

ChrisF
A: 

I knocked up a quick console app that does something like this, can't attest to how performant it is though :)

using System;

namespace RandomEnum
{
    class Program
    {
        private enum TestEnum
        {
            One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
        };

        static void Main(string[] args)
        {
            string[] names = Enum.GetNames(typeof (TestEnum));

            Random random = new Random();

            int randomEnum = random.Next(names.Length);

            var ret = Enum.Parse(typeof (TestEnum), names[randomEnum]);

            Console.WriteLine(ret.ToString());
        }
    }
}
Russ C