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

时间:2014-12-31 08:18:34

标签: c# enums

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

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

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

我需要创建一个包含字符串列表中所有颜色的整数列表。 例如 - 对于列表{“蓝色”,“红色”,“黄色”}我想创建一个列表 - {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;
}

3 个答案:

答案 0 :(得分:8)

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

您可以使用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();

答案 1 :(得分:3)

只需将每个字符串投影到适当的枚举值(当然,确保字符串是有效的枚举名称):

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

结果:

2, 1, 7

如果可能包含不是枚举成员名称的字符串,那么您应该使用字典方法或使用Enum.TryParse检查名称是否有效:

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;
}

答案 2 :(得分:2)

使用Enum.Parse并将其转换为int。

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

我已将Enum.Parse的第三个参数用于true,以使解析案例不敏感。你可以通过传递false或完全忽略参数来区分大小写。

相关问题