How do I select a random value from an enumeration?

前端 未结 9 813
眼角桃花
眼角桃花 2020-12-04 07:54

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 f

相关标签:
9条回答
  • 2020-12-04 08:22

    Here's an alternative version as an Extension Method using 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());
            }
        }           
    }
    

    Two
    One
    Four
    Four
    Four
    Three
    Two
    Four
    One
    Three

    0 讨论(0)
  • 2020-12-04 08:22

    Personally, I'm a fan of extension methods, so I would use something like this (while not really an extension, it looks similar):

    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);
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 08:22

    Adapted as a Random class extension:

    public static class RandomExtensions
    {   
        public static T NextEnum<T>(this Random random)
        {
            var values = Enum.GetValues(typeof(T));
            return (T)values.GetValue(random.Next(values.Length));
        }
    }
    

    Example of usage:

    var random = new Random();
    var myEnumRandom = random.NextEnum<MyEnum>();
    
    0 讨论(0)
提交回复
热议问题