How to check if a value is present in one of the three enums in C#?

I want to select the category of the string value checking in three enums.

CategoryEnum.cs

Category1 = 1,
Category2,
Category3

Category1.cs

Value1 = 1,
Value2 = 2

Category2.cs

Value3 = 1,
Value4 = 2

Category3.cs

Value5 = 1,
Value6 = 2

I have a string testValue and I want to check if it is present in Category1, Category2, or Category3 Enums and then return the string CategoryType in which the value is present. How to do this in C#?

1 answer

  • answered 2022-05-04 10:45 Palle Due

    If you add the values to a dictionary, you only have to use reflection once. Define

    public enum CategoryEnum
    {
        Category1 = 1,
        Category2,
        Category3
    }
    
    public enum Category1
    {
        Value1 = 1,
        Value2 = 2
    }
    
    public enum Category2
    {
        Value3 = 1,
        Value4 = 2
    }
    
    public enum Category3
    {
        Value5 = 1,
        Value6 = 2
    }
    
    private static Dictionary<string, CategoryEnum> valueDict = new Dictionary<string, CategoryEnum>();
    

    And

    private string[] GetEnumValues<T>()
    {
        T[] myEnumMembers = (T[])Enum.GetValues(typeof(T));
        return myEnumMembers.Select(e=>e.ToString()).ToArray();
    }
    

    Then you can initialize the dictionary like this:

    foreach (var s in GetEnumValues<Category1>())
    {
        valueDict.Add(s, CategoryEnum.Category1);
    }
    foreach (var s in GetEnumValues<Category2>())
    {
        valueDict.Add(s, CategoryEnum.Category2);
    }
    foreach (var s in GetEnumValues<Category3>())
    {
        valueDict.Add(s, CategoryEnum.Category3);
    }
    

    And look up a value like this:

    var cat2Val3 = Category2.Value3;
    Console.WriteLine(valueDict[cat2Val3.ToString()]);
    

    Be sure not to overlap value names, though.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum