【问题标题】:Get matching enum int values from list of strings从字符串列表中获取匹配的枚举 int 值
【发布时间】:2014-12-31 08:18:33
【问题描述】:

我有一个具有不同 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 如果这是你想要的。
  • 它可以帮助我从我的代码中删除字典,但它不会取代我的 foreach 循环。我会编辑我的问题。谢谢。

标签: c# enums


【解决方案1】:
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();

【讨论】:

  • 感谢您的详细解答! :)
  • @TamarG 很高兴为您提供帮助。
【解决方案2】:

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

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 不客气,我还添加了解析不是枚举名称的字符串的选项
【解决方案3】:

使用 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 以使 Parsing 不区分大小写。您可以通过仅传递 false 或完全忽略参数来使其区分大小写。

【讨论】:

  • 感谢您的详细解答! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 2020-07-11
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
相关资源
最近更新 更多