Search for a string in Enum and return the Enum

C#StringEnumeration

C# Problem Overview


I have an enumeration:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

and I have a string:

string colour = "Red";

I want to be able to return:

MyColours.Red

from:

public MyColours GetColour(string colour)

So far i have:

public MyColours GetColours(string colour)
{
    string[] colours = Enum.GetNames(typeof(MyColours));
    int[]    values  = Enum.GetValues(typeof(MyColours));
    int i;
    for(int i = 0; i < colours.Length; i++)
    {
        if(colour.Equals(colours[i], StringComparison.Ordinal)
            break;
    }
    int value = values[i];
    // I know all the information about the matched enumeration
    // but how do i convert this information into returning a
    // MyColour enumeration?
}

As you can see, I'm a bit stuck. Is there anyway to select an enumerator by value. Something like:

MyColour(2) 

would result in

MyColour.Green

C# Solutions


Solution 1 - C#

check out System.Enum.Parse:


enum Colors {Red, Green, Blue}




// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");

// your code: Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");

Solution 2 - C#

You can cast the int to an enum

(MyColour)2

There is also the option of Enum.Parse

(MyColour)Enum.Parse(typeof(MyColour), "Red")

Solution 3 - C#

Given the latest and greatest changes to .NET (+ Core) and C# 7, here is the best solution:

var ignoreCase = true;
Enum.TryParse("red", ignoreCase , out MyColours colour);

colour variable can be used within the scope of Enum.TryParse

Solution 4 - C#

All you need is Enum.Parse.

Solution 5 - C#

I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

public MyColours GetColours(string colour)
{  
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;
}

Solution 6 - C#

var color =  Enum.Parse<Colors>("Green");

Solution 7 - C#

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

Solution 8 - C#

Try this method.

public static class Helper
{
  public static T FromStr<T>(string str) where T : struct, System.Enum
    => System.Enum.TryParse<T>(value:str,ignoreCase:true,result:out var result)
    ? result
    : default;
  public static T? FromStrNull<T>(string str) where T : struct, System.Enum
    => System.Enum.TryParse<T>(value: str,ignoreCase: true,result: out var result)
    ? result
    : null;
}

And use it like this

var color = Helper.FromStr<MyColours>("red");

Solution 9 - C#

As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.

Solution 10 - C#

class EnumStringToInt // to search for a string in enum
{
    enum Numbers{one,two,hree};
    static void Main()
    {
        Numbers num = Numbers.one; // converting enum to string
        string str = num.ToString();
        //Console.WriteLine(str);
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
        try
        {
            for (int i = 0; i <= getnum.Length; i++)
            {
                if (str1.Equals(getnames[i]))
                {
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Value not found!", ex);
        }
    }
}

Solution 11 - C#

One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided [here][1]

With this you can define your enumerations as classes (the examples are in vb.net):

> < StringEnumRegisteredOnly(), DebuggerStepThrough(), > ImmutableObject(True)> Public NotInheritable Class > eAuthenticationMethod Inherits StringEnumBase(Of > eAuthenticationMethod) > > Private Sub New(ByVal StrValue As String) > MyBase.New(StrValue)
End Sub > > < Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")

> < Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")
> End Class

And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

I've been using this for a long time now and it makes the code more clear in intent. [1]: http://www.codeproject.com/KB/vb/StringEnum.aspx?msg=2457746

Solution 12 - C#

(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0

Solution 13 - C#

You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>

The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse - instead you end up writing something like this in your code:

MyColours colour = Enum<MyColours>.Parse(stringValue); 

Or check out some of the comments in the same post which talk about using an extension method to achieve similar.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt ClarksonView Question on Stackoverflow
Solution 1 - C#JMarschView Answer on Stackoverflow
Solution 2 - C#GuvanteView Answer on Stackoverflow
Solution 3 - C#RomanView Answer on Stackoverflow
Solution 4 - C#Bruno BrantView Answer on Stackoverflow
Solution 5 - C#ColinView Answer on Stackoverflow
Solution 6 - C#pampiView Answer on Stackoverflow
Solution 7 - C#OregonGhostView Answer on Stackoverflow
Solution 8 - C#Waleed A.K.View Answer on Stackoverflow
Solution 9 - C#AddysView Answer on Stackoverflow
Solution 10 - C#RajaView Answer on Stackoverflow
Solution 11 - C#AndoView Answer on Stackoverflow
Solution 12 - C#Sandeep ShekhawatView Answer on Stackoverflow
Solution 13 - C#Julian MartinView Answer on Stackoverflow