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