Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to Dictionary in C#

I have searched this online, but I can't find the answer I am looking for.

Basically I have the following enum:

public enum typFoo : int {    itemA : 1,    itemB : 2    itemC : 3 } 

How can I convert this enum to Dictionary so that it stores in the following Dictionary?

Dictionary<int,string> myDic = new Dictionary<int,string>(); 

And myDic would look like this:

1, itemA 2, itemB 3, itemC 

Any ideas?

like image 824
daehaai Avatar asked Apr 07 '11 15:04

daehaai


2 Answers

Try:

var dict = Enum.GetValues(typeof(fooEnumType))                .Cast<fooEnumType>()                .ToDictionary(t => (int)t, t => t.ToString() ); 
like image 141
Ani Avatar answered Oct 27 '22 11:10

Ani


See: How do I enumerate an enum in C#?

foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) ) {     mydic.Add((int)foo, foo.ToString()); } 
like image 31
Zhais Avatar answered Oct 27 '22 11:10

Zhais