Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary from enum values

Tags:

c#

enums

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!

like image 657
Mdb Avatar asked Dec 03 '25 04:12

Mdb


1 Answers

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());
like image 72
drch Avatar answered Dec 04 '25 17:12

drch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!