【发布时间】: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 循环。我会编辑我的问题。谢谢。