代码之家  ›  专栏  ›  技术社区  ›  mafu

How do I select a random value from an enumeration?

  •  151
  • mafu  · 技术社区  · 15 年前

    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.)

    7 回复  |  直到 8 年前
        1
  •  248
  •   Darin Dimitrov    15 年前
    Array values = Enum.GetValues(typeof(Bar));
    Random random = new Random();
    Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));
    
        2
  •  55
  •   mafu    10 年前

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

    static T RandomEnumValue<T> ()
    {
        var v = Enum.GetValues (typeof (T));
        return (T) v.GetValue (new Random ().Next(v.Length));
    }
    

    测试:

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

    -gt;

    Tuesday
    Saturday
    Wednesday
    Monday
    Friday
    Saturday
    Saturday
    Saturday
    Friday
    Wednesday
    

    Updated: This answer originally used OrderBy (x => _Random.Next()).FirstOrDefault () to select a random element. Only use it if you are irrationally attracted to shuffling by random keys. In any other case, use the accepted answer by Darin Dimitrov instead, which I incorporated in this answer later.

        3
  •  2
  •   Tim Robinson    15 年前

    呼叫 Enum.GetValues ;这将返回一个数组,该数组表示枚举的所有可能值。从这个数组中选择一个随机项。Cast that item back to the original enum type.

        4
  •  2
  •   WHol    10 年前

    Here is a generic function for it. Keep the RNG creation outside the high frequency code.

    public static Random RNG = new Random();
    
    public static T RandomEnum<T>()
    {  
        Type type = typeof(T);
        Array values = Enum.GetValues(type);
        lock(RNG)
        {
            object value= values.GetValue(RNG.Next(values.Length));
            return (T)Convert.ChangeType(value, type);
        }
    }
    

    使用实例:

    System.Windows.Forms.Keys randomKey = RandomEnum<System.Windows.Forms.Keys>();
    
        5
  •  2
  •   Breno Angelotti    8 年前

    You could just do this:

    var rnd = new Random();
    return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);
    

    No need to store arrays

        6
  •  1
  •   Dan Champagne    10 年前

    就我个人而言,我非常喜欢扩展方法,所以我会使用类似的方法(虽然不是真正的扩展,但看起来很相似):

    public enum Options {
        Zero,
        One,
        Two,
        Three,
        Four,
        Five
    }
    
    public static class RandomEnum {
        private static Random _Random = new Random(Environment.TickCount);
    
        public static T Of<T>() {
            if (!typeof(T).IsEnum)
                throw new InvalidOperationException("Must use Enum type");
    
            Array enumValues = Enum.GetValues(typeof(T));
            return (T)enumValues.GetValue(_Random.Next(enumValues.Length));
        }
    }
    
    [TestClass]
    public class RandomTests {
        [TestMethod]
        public void TestMethod1() {
            Options option;
            for (int i = 0; i < 10; ++i) {
                option = RandomEnum.Of<Options>();
                Console.WriteLine(option);
            }
        }
    
    }
    
        7
  •  1
  •   LW001 Rohan Muhammad    8 年前

    Here's an alternative version as an Extension Method 使用 LINQ .

    using System;
    using System.Linq;
    
    public static class EnumExtensions
    {
        public static Enum GetRandomEnumValue(this Type t)
        {
            return Enum.GetValues(t)          // get values from Type provided
                .OfType<Enum>()               // casts to Enum
                .OrderBy(e => Guid.NewGuid()) // mess with order of results
                .FirstOrDefault();            // take first item in result
        }
    }
    
    public static class Program
    {
        public enum SomeEnum
        {
            One = 1,
            Two = 2,
            Three = 3,
            Four = 4
        }
    
        public static void Main()
        {
            for(int i=0; i < 10; i++)
            {
                Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
            }
        }           
    }
    











    推荐文章