I have a enum of colors with different int values
enum Colors { Red = 1, Blue = 2, Green = 5, Yellow = 7, Pink = 10, Black = 15 };
and I have a list of strings that contains color names (I can suppose that all the names in the list exists in the enum).
I need to create a list of ints of all the colors in the list of strings. For example - for the list {"Blue", "red", "Yellow"} I want to create a list - {2, 1, 7}. I don't care about the order.
My code is the code below. I use a dictionary and foreach-loop. Can I do it with linq and make my code shorter and simpler?
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();
You can use Enum.Parse(Type, String, Boolean) method. But it will throw exception if not found the value in Enum.
In such situation you can filter the array firstly with the help of IsDefined
method.
var res = colorList.Where(x=> Enum.IsDefined(typeof(Colors), x))
.Select(x => (int)Enum.Parse(typeof(Colors), x, true)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With