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

本文关键字:枚举 int 字符串 列表 获取 | 更新日期: 2023-09-27 18:35:41

我有一个具有不同 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;
}

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

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();

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

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

使用 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 或完全忽略参数来使其区分大小写。