Mdb
Mdb

Reputation: 8556

Create a dictionary from enum values

I have the following enum:

 public enum Brands
    {
        HP = 1,
        IBM = 2,
        Lenovo = 3
    }

From it I want to make a dictionary in format:

// key = name + "_" + id
// value = name

var brands = new Dictionary<string, string>();
brands[HP_1] = "HP",
brands[IBM_2] = "IBM",
brands[Lenovo_3] = "Lenovo"

So far I have done this, but have difficulties creating the dictionary from the method:

public static IDictionary<string, string> GetValueNameDict<TEnum>()
        where TEnum : struct, IConvertible, IComparable, IFormattable
        {
            if (!typeof(TEnum).IsEnum)
                throw new ArgumentException("TEnum must be an Enumeration type");

            var res = from e in Enum.GetValues(typeof (TEnum)).Cast<TEnum>()
                      select // couldn't do this

            return res;
        }

Thanks!

Upvotes: 2

Views: 3159

Answers (2)

user2870613
user2870613

Reputation: 31

//Use this code :

 Dictionary<string, string> dict = Enum.GetValues(typeof(Brands)).Cast<int>().ToDictionary(ee => ee.ToString(), ee => Enum.GetName(typeof(Brands), ee));

Upvotes: 3

drch
drch

Reputation: 3080

You can use Enumerable.ToDictionary() to create your Dictionary.

Unfortunately, the compiler won't let us cast a TEnum to an int, but because you have already asserted that the value is an Enum, we can safely cast it to an object then an int.

var res = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => e + "_" + (int)(object)e, e => e.ToString());

Upvotes: 9

Related Questions