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
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...
See more on this question at Stackoverflow