0

Is there a clever way to get an enum value by comparing a substring a la String.Contains with the enum? I checked this implementation (Convert a string to an enum in C#), but would like to have an intelligent extension doing the same but including substrings comparison, something like TryParse with an option to check the whole substring of the enum values.

    public static void Main()
{
    string a = "HANS";
    GetName(a); // prints Hans
    
    string a1 = "Peter";
    GetName(a1); // should print enum value "WolfgangPeterDietrich " containing the substring "Peter"
}

public enum MyNames
{
    Hans = 0,
    WolfgangPeterDietrich = 3,
}

public static void GetName(string a)
{
    MyNames dif;
    // this works fine, ignore case
    if (Enum.TryParse(a, true, out dif))
    {      
        System.Console.WriteLine(dif.ToString());
    }
    // ToDo: check for substring ??
}
KevinNivek
  • 21
  • 7

3 Answers3

1

This approach takes the first occurrence found, and is case insensitive.

public static void GetName(string a)
{
    string? result = Enum.GetNames<MyNames>()
        .FirstOrDefault(x => x.Contains(a, StringComparison.OrdinalIgnoreCase));
    System.Console.WriteLine(result);
}
Magnetron
  • 7,495
  • 1
  • 25
  • 41
0

Just a prototype to fix with boundary cases and assertions:

public static T EnumNameContains<T>(string substringOfName) where T: struct
{
    return (T)Enum.Parse(typeof(T), 
        Enum.GetNames(typeof(T)).FirstOrDefault(
            name => name.IndexOf(substringOfName,StringComparison.CurrentCultureIgnoreCase) >= 0));
}

I guess can help.

GibbOne
  • 629
  • 6
  • 10
  • 1
    nice one following https://stackoverflow.com/questions/28279933/performance-of-indexofchar-vs-containsstring-for-checking-the-presence-of-a – KevinNivek Oct 06 '21 at 12:23
0

You can try this

public static void GetName(string a)
        {
            MyNames dif;
            // this works fine, ignore case
            if (Enum.TryParse(a, true, out dif))
            {
                System.Console.WriteLine(dif.ToString());
            }
            else
            {
                var result = Enum.GetNames(typeof(MyNames)).Where(dd => dd.Contains(a, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                System.Console.WriteLine(result);
            }
            
        }
decoder
  • 886
  • 22
  • 46