从字符串列表中获取匹配的枚举整数值

5

我有一个包含不同 int 值的颜色枚举。

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

我有一个字符串列表,其中包含颜色名称(假设列表中的所有名称都存在于枚举中)。
我需要创建一个整数列表,其中包含列表中所有颜色的对应整数值。 例如 - 对于列表{"Blue", "red", "Yellow"},我想创建一个列表 - {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;
}

你看过Enum.TryParse ?。一旦你有了枚举,如果需要的话,你可以将其强制转换回int。 - StuartLC
它帮助我从代码中删除了字典,但它并没有替换我的foreach循环。我会编辑我的问题。谢谢。 - TamarG
3个回答

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

你可以使用 Enum.Parse(Type, String, Boolean) 方法。但是如果在枚举中没有找到该值,它将会抛出异常。 在这种情况下,你可以先使用 IsDefined 方法过滤数组。
 var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors), x))
                    .Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();

感谢您详细的回答! :) - TamarG
@TamarG 很高兴能帮忙。 - Farhad Jabiyev

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

谢谢你详细的回答! :) - TamarG
1
@TamarG 没问题,我还添加了一个选项,可以解析不是枚举名称的字符串。 - Sergey Berezovskiy

2

使用 Enum.Parse 方法并将其转换为整数。

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

我已经使用了Enum.Parse的第三个参数,将其设置为true以使解析不区分大小写。如果只传递false或完全忽略该参数,则可以使其区分大小写。


感谢您详细的回答! :) - TamarG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接