从字符串列表中获取匹配的enum int值

Tam*_*arG 3 c# enums

我有一个具有不同int值的颜色枚举

enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };
Run Code Online (Sandbox Code Playgroud)

我有一个包含颜色名称的字符串列表(我可以假设列表中的所有名称都存在于枚举中).

我需要在字符串列表中创建所有颜色的整数列表.例如 - 对于列表{"蓝色","红色","黄色"}我想创建一个列表 - {2,1,7}.我不在乎订单.

我的代码是下面的代码.我使用字典和foreach循环.我可以用linq做这件事,让我的代码更短更简单吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Far*_*yev 8

var res = colorList.Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();
Run Code Online (Sandbox Code Playgroud)

您可以使用Enum.Parse(Type,String,Boolean)方法.但如果没有在Enum中找到该值,它将抛出异常.在这种情况下,您可以先使用方法过滤数组.IsDefined

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