Efficient substring matching on enum

Viewed 48

I have an enum like so

public enum Colors
{
    Green,
    LightGreen,
    Blue
}

and given a string

string substringToMatch = "Green"

I'd like to be able to retrieve all elements in my enum that contain my string as a substring efficiently - ideally even type-insensitive.

So far I've been able to find exact matches with Enum.TryParse, but haven't found a way to do substring matching as well.

1 Answers
IEnumerable<Colors> matchingColors = Enum.GetValues<Colors>()
    .Where(c => c.ToString().Contains(substringToMatch, StringComparison.InvariantCultureIgnoreCase));

Demo: https://dotnetfiddle.net/KmsyvP

Edit: for .NET framework you have to change 2 things, no generic Enum.GetValues and no String.Contains with StringComparison overload. So you can use:

IEnumerable<Colors> matchingColors = Enum.GetValues(typeof(Colors)).Cast<Colors>()
    .Where(c => c.ToString().IndexOf(substringToMatch, StringComparison.InvariantCultureIgnoreCase) >= 0);
Related