1

How to get all values of enum with integer value in this example

enum colour { red = 1, green = 1, blue = 1, yellow = 2, cyan = 2, purple = 2 }

I mean, by inputting 1, I want output red, green, blue

0

1 Answer 1

3

Well, firstly I would strongly recommend that you don't do this.

Having multiple names for the same value is a really bad idea, IMO. However, you can do it with reflection:

using System;
using System.Collections.Generic;
using System.Linq;

enum Color
{
    Red = 1,
    Green = 1,
    Blue = 1,
    Yellow = 2,
    Cyan = 2,
    Purple = 2
}

class Test
{
    static void Main()
    {
        foreach (var name in GetColorNames(1))
        {
            Console.WriteLine(name);
        }
    }

    static IEnumerable<string> GetColorNames(int value)
    {
        return Enum.GetNames(typeof(Color))
                   .Where(name => (int) Enum.Parse(typeof(Color), name) == value);
    }
}

Personally I would have separate values in the enum instead, and then have a Lookup<int, Color> or something like that. Aside from anything else, it would be very confusing to have something like:

Color color = Color.Blue;

... and then see Red in the debugger or other diagnostics...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.