Get matching enum int values ​​from a list of strings

I have an enumeration of colors with different int values

enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };

      

and I have a list of strings containing the names of the colors (I can assume that all the names in the list exist in the enum).

I need to create a list of ints of all colors in a list of strings. For example - for the list {"Blue", "Red", "Yellow"} I want to create a list - {2, 1, 7}. I don't care about order.

My code is the code below. I am using a dictionary and foreach loop. Can I do this with linq and make the code shorter and simpler?

public enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };

public List<int> getColorInts(List<string> myColors)
{
    // myColors contains strings like "Red", "Blue"..

    List<int> colorInts = new List<int>();
    foreach (string color in myColors)
    {
         Colors result;
         bool success = Enum.TryParse(color , out result);
         if (success)
         {
             colorInts .Add((int)result);
         }
    }
    return colorInts;
}

      

+3


source to share


3 answers


var res = colorList.Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();

      

You can use the Enum.Parse (Type, String, Boolean) method . But it will throw an exception if no value is found in the Enum. In such a situation, you can first filter the array using the method IsDefined

.



 var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors), x))
                    .Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();

      

+7


source


Just project each line to the corresponding enum value (of course, make sure the lines are valid enumeration names):

myColors.Select(s => (int)Enum.Parse(typeof(Colors), s, ignoreCase:true))

      

Result:



2, 1, 7

      

If it is possible to have a string that is not the name of an enumeration member, then you should use your dictionary approach, or use Enum.TryParse

to check if the name is valid:

public IEnumerable<int> GetColorsValues(IEnumerable<string> colors)
{
    Colors value;
    foreach (string color in colors)
        if (Enum.TryParse<Colors>(color, true, out value))
            yield return (int)value;
}

      

+3


source


Use Enum.Parse

and pass it to int.

public List<int> GetColorInts(IEnumerable<string> myColors)
{
    return myColors
        .Select(x => Enum.Parse(typeof(Colors), x, true))
        .Cast<int>()
        .ToList();
}

      

I used the third parameter Enum.Parse

to true to make it case insensitive. You can make it case sensitive by simply passing false or by completely ignoring the argument.

+2


source







All Articles