Bick
Bick

Reputation: 18521

Populate dictionary from enum

I have the following enum:

public enum LifeCycle
{
    Pending = 0,
    Approved = 1,
    Rejected = 2,
}

And I want to create

Dictionary<int, string> LifeCycleDict;  

from the enum value and its toString

Is there a way to do it with linq?
(The equivelant to java's enum.values ) Thanks.

Upvotes: 2

Views: 1837

Answers (1)

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

Dictionary<int, string> LifeCycleDict = Enum.GetNames(typeof(LifeCycle))
    .ToDictionary(Key => (int)Enum.Parse(typeof(LifeCycle), Key), value => value);

OR

Dictionary<int, string> LifeCycleDict = Enum.GetValues(typeof(LifeCycle)).Cast<int>()
    .ToDictionary(Key => Key, value => ((LifeCycle)value).ToString());

OR

Dictionary<int, string> LifeCycleDict = Enum.GetValues(typeof(LifeCycle)).Cast<LifeCycle>()
    .ToDictionary(t => (int)t, t => t.ToString());

Upvotes: 6

Related Questions