Selecting enum values based on key names
c#, enums, linq
Solution
Here's a compromise set of code - it's not as clean as what you're looking for, but it's far better than the foreach loop version.
Enum.GetValues(typeof(Animals)).OfType<Animals>()
.Where(x => x.ToString().StartsWith("Cat"))
.Select(x => (int)x).ToArray();
Problem
I have an enum like so: ``` public enum Animals { CatOne = 12, CatTwo = 13, CatThree = 14, DogOne = 21, DogTwo = 22 }; ``` Great. Now I want to get the values of all the cats.. What I'm trying to do is this: ``` public static int[] GetCatValues() { List<int> catValues = new List<int>(); foreach(var cat in Enum.GetNames(typeof(Animals))) { Animals animal; if(cat.StartsWith("Cat")) { Enum.TryParse(cat, out animal); catValues.Add((int)animal); } } return catValues.ToArray(); } ``` Which works okay. Except it looks ugly. Why can't I do something like ``` Animals .Select(r => (int)r) .Where(r => r.StartsWith("Cat")) .ToArray(); ``` I know that doesn't work. So is there a better way of getting all values of enum that starts with certain string. I know I could probably use regex to avoid false positives, but, I am keeping it simple for now. Thanks.