How to remove enum from string?

Viewed 461

I have a set of enum values and an input string, and in case the string has a suffix which is one of the enum names, I want to delete it.

For example, let's say I have

enum colors { red, blue, green, white }

And I receive the input string "str = evergreen", I want to do something like

if (str.endsWith(colors)) {
   output = str.trimSuffix(colors)
}

and get the string ever in output. Modifying str itself instead of saving it to a new variable is also fine.

is there a simple and/or elegant way to do it without hard coding the enum as array of strings and iterate over it?

1 Answers

This code will remove any suffix from str that is defined in the enum below

var values = Enum.GetNames(typeof(colors));
var str = "evergreen";

var suffix = values.OrderByDescending(v => v.Length)
    .FirstOrDefault(v => str.EndsWith(v));

if(suffix != null)
{
    str = str.Substring(0, str.Length - suffix.Length);
}

enum colors { 
   red,
   blue,
   green,
   white 
}
Related