gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:22:14 25 4
gpt4 key购买 nike

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

最佳答案

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

关于c# - 从字符串列表中获取匹配的枚举 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27718223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com