Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get matching enum int values from list of strings

Tags:

c#

enums

I have a enum 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 that contains color names (I can suppose that all the names in the list exists in the enum).

I need to create a list of ints of all the colors in the 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 the order.

My code is the code below. I use a dictionary and foreach-loop. Can I do it with linq and make my 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;
}
like image 672
TamarG Avatar asked Dec 08 '22 05:12

TamarG


1 Answers

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

You can use Enum.Parse(Type, String, Boolean) method. But it will throw exception if not found the value in Enum. In such situation you can filter the array firstly with the help of IsDefined method.

 var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors), x))
                    .Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();
like image 56
Farhad Jabiyev Avatar answered Jan 11 '23 05:01

Farhad Jabiyev