Thursday, 27 August 2015

Filter an Enum By String Value in C#

I have an enum declared and wanted to get all items in the enum that contained certain text. Well, this can be done using Linq and here's an example:

public enum Animals
{
    Dog,
    Cat,
    Mouse,
    Sheep
}

var filteredAnimals = Enum.GetValues(typeof(Animals))
    .Cast<Animals>()
    .Where(t => !t.ToString().Contains("e"))
    .ToList()

This gives a list of Mouse and Sheep.

Further to that, if wanted to get the maximum integer value of your filtered list, then you could use this:

public enum Animals
{
    Dog,
    Cat,
    Mouse,
    Sheep
}

var filteredAnimals = Enum.GetValues(typeof(Animals))
    .Cast<Animals>()
    .Where(t => !t.ToString().Contains("a"))
    .Cast<int>()
    .Max()

This gives us 1 as Cat is the highest enum that contains an "a"

No comments:

Post a Comment