Get a random listing from a selected group

For a group of about 20 listings, which I cannot change.

Im looking for an elegant solution to generate a random enumeration from a specific pattern (i.e. 2, 7, 18)

I could put them in an arraylist, but I thought I would ask if there was anything else that I could try.

+3
source share
6 answers

If your values ​​are of the same type:

MyEnum[] values = { MyEnum.Value2, MyEnum.Value7, MyEnum.Value18 };
Random random = new Random();
MyEnum randomValue = values[random.Next(values.Length)];
+3
source

You can get all the values ​​for this type of enumeration with:

var values = Enum.GetValues(typeof(MyEnum));
+2
source

- , , - .

, , .

0

I knocked out a quick console application that does something like this, cannot confirm how effective it is :)

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());
        }
    }
}
0
source

Why is it so hard ...

private static T GetRandomEnum<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>().OrderBy(e => Guid.NewGuid()).First();
}

Using:

GetRandomEnum<MyEnumType>()
0
source
    enum days
    {
        sunday,monday,tuesday,wednesday,thursday,friday,saturday
    }
    static void Main(string[] args)
    {
        Random r = new Random();
        Console.WriteLine(Enum.GetNames(typeof(days))[r.Next(1, 7)]);    
        Console.ReadKey();
    }
0
source

Source: https://habr.com/ru/post/1749398/


All Articles