'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#?
Solution 1:[1]
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.
Solution 2:[2]
I fixed it by adding another value in the categoryenum "Unknown" And then used this code. Its a little tradeoff but simple.
private CategoryEnum GetColumnCategory(string value)
{
if (Enum.TryParse(value, out Category1 category1))
{
return CategoryEnum.Category1;
}
else if (Enum.TryParse(dataType, out Category2 category2))
{
return CategoryEnum.Category2;
}
else if (Enum.TryParse(dataType, out Category3 category3))
{
return CategoryEnum.Category3;
}
else
{
return CategoryEnum.Unknown;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Palle Due |
| Solution 2 | Shishank Jain |
