Reputation: 4397
I want do achieve a pretty simple task, but the thing is to do this in a nice, simple way. We all want to write pretty code that is easy to maintain, quick to understand. I have a problem that experienced C# developers may help me with.
I want to create a dictionary
, where keys
(string[]
) are names of enum values
and values
are their ecorresponding enum values
. If this is confusing, let me give you a short example:
enum Animals
{
Dog,
Cat,
Fish
}
Dictionary<string, Animals> result = new Dictionary<string, Animals>()
{
{ "Dog", Animals.Dog },
{ "Cat", Animals.Cat },
{ "Fish", Animals.Fish }
};
Here is my approach:
a little extension:
public static IEnumerable<T> GetValues<T>() => Enum.GetValues(typeof(T)).Cast<T>();
and then the construction:
var result = Utils
.GetValues<Animals>()
.ToDictionary(x => x.ToString(), x => x);
How would you, experienced devs, approach this problem to write it in a clearer way? Or perhaps there is a trick with enums that would enable a quick lookup like "give me an enum which name satisfies my condition".
Upvotes: 3
Views: 86
Reputation: 391704
To take a string and convert it to its matching enum value, or even fail if there is no matching enum value you should use Enum.TryParse:
Animals animal;
if (Enum.TryParse("Dog", out animal))
// animal now contains Animals.Dog
else
// animal "undefined", there was no matching enum value
Upvotes: 3
Reputation: 4340
The Parse
method of the Enum
type is what I think you are looking for.
var value = Enum.Parse(typeof(T), "Dog");
Upvotes: 2