简体   繁体   中英

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!

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());

//使用以下代码:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM