morty
morty

Reputation: 90

Get Enum names corresponding to the integer value when Enum is flagged

Consider the following enum:

enum Color 
{
  None = 0,
  Yellow = 1,
  Green = 2,
  Blue = 4
}
var enumType = typeof(Color);

var number = (int)(Color.Yellow | Color.Green);
// number equals to 3

Now I want the reverse of the above operation. I wanna know what enumerations lead to the number 3. like:

string[] names = GetEnumNames(enumType, 3);
// It should return an array { "Yellow", "Green" }

I have tried Enum.ToObject and I know that it returns the Enum with "Yellow" and "Green" in it. But how can I get the list of names?

Note: Just to mention, I only know the type of the Enum at runtime.

Upvotes: 0

Views: 739

Answers (6)

Idle_Mind
Idle_Mind

Reputation: 39122

Using the Flags approach suggested by vivek nuna, you could cheat and do:

[Flags]
enum Color
{
    None = 0,
    Yellow = 1,
    Green = 2,
    Blue = 4
}

static void Main(string[] args)
{           
    var colorCombo = Color.Yellow | Color.Green;
    var colors = HasFlags(colorCombo);
    Console.WriteLine(String.Join(", ", colors));

    Console.Write("Press Enter to Quit");
    Console.ReadLine();
}

public static IEnumerable<String> HasFlags(Enum value)
{
    return value.ToString().Split(",".ToCharArray()).Select(v => v.Trim());
}

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

Here's another approach similar to what Phil Ross posted, but using HasFlag:

Color colorCombo = Color.Yellow | Color.Green;

String[] colors = Enum.GetValues(typeof(Color)).Cast<Color>()
    .Where(i => i != 0 && colorCombo.HasFlag(i)).Select(i => i.ToString()).ToArray();

Console.WriteLine(String.Join(", ", colors));

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

You need to use [Flags] with enum.

[Flags]
public enum Color 
{
  None = 0,
  Yellow = 1,
  Green = 2,
  Blue = 4
}

var twoOrThree = Color.Green | Color.Blue;
Console.WriteLine(twoOrThree.ToString());  

It will print Green, Blue

Upvotes: 1

Phil Ross
Phil Ross

Reputation: 26090

You can use Enum.GetValues() to get all the values and then filter to find those that match:

IEnumerable<string> GetEnumNames<T>(int value)
{
    return Enum.GetValues(typeof(T))
        .Cast<int>()
        .Where(i => i != 0 && (i & value) == i)
        .Cast<T>()
        .Select(i => i.ToString()); 
}

GetEnumNames<Color>(3); // => {"Yellow", "Green"}

Upvotes: 1

Rhys Wootton
Rhys Wootton

Reputation: 182

Whilst you could get all the names into a string[] and then just reference that, Enums have a function that allows you to get the name associated with a value.

enum Color 
{
  None = 0,
  Yellow = 1,
  Green = 2,
  Blue = 4
}

public void SomeMethod() {
    string enumName = enum.GetName(typeof(Color), 2)
    // enumName = Green
}

MSDN has a good example on it as well

Upvotes: 0

Tavershima
Tavershima

Reputation: 141

To get the items of enum, type

string[] enums = Enum.GetNames(typeof(myEnum))

Upvotes: -1

Related Questions