Enum to Dictionary in C#

Enum to Dictionaryint, string in C#

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

foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
mydic.Add((int)foo, foo.ToString());
}

Using Enum and | as dictionary key

Unless otherwise specified, an enum maps to an integral value. Dictionary lookups will be based on the integral value of the enumerated value.

Since you didn't override the values assigned to your enum, they number from zero. This means AirForce == 0, Army == 1, and so on.

When you combine AirForce | Army | Marines, you're really doing 0 | 1 | 3, which is 3.

The way you've set up your dictionary, you've added entries for the integral values of 3 (with the bitwise operand), 2 (for Navy) and 4 (for Marines).

I'm afraid the simplest approach for what you want is to add an explicit entry for each branch of the military.

Create a dictionary from enum values

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

Convert Enum with [DescriptionAttribute] to Dictionarystring,int

According to an answer https://stackoverflow.com/a/2650090/643095,

string description = Enumerations.GetEnumDescription((MyEnum)value);

Where value is int enum value.

You can use something like this:

accountViewModel.Genders = Enum.GetValues(typeof(Account.Genders))
.Cast<Account.Genders>()
.ToDictionary(t => Enumerations.GetEnumDescription((Genders)t), t => (int)t);

Enum as Dictionary keys

I believe that's because of covariance.

In short:

aDictionary will be a Dictionary<SomeEnum, SomeClass>, but in the current context it is known as Dictionary<Enum, SomeClass>.

Had your declaration been allowed, the compiler should afterwards let you do:

aDictionary.Add(someValueFromAnotherEnumUnrelatedToSomeEnum, aValue);

which is obviously inconsistent with respect to the actual type of the dictionary.

That's why co-variance is not allowed by default and you have to explicitly enable it in cases where it makes sense.

The conclusion is that you have to specify the type exactly:

Dictionary<SomeEnum, SomeClass> aDictionary = 
new Dictionary<SomeEnum, SomeClass>();

Convert dictionary, with string key, to dictionary with enum key using Generics

You can solve it by injecting the converter for the key; from string to the wanted key type T.

Here's an example:

public enum Product { Product1, Product2, Product3 };
public enum Fund { Fund1, Fund2, Fund3 }
//...and lots of different enums

private static Dictionary<T, double> ConvertDict<T>(
Dictionary<string, double> dict,
Func<string, T> convertKey)
{
var returnDict = new Dictionary<T, double>();

foreach (var kvp in dict)
{
returnDict.Add(convertKey(kvp.Key), kvp.Value);
}

return returnDict;
}

private static Product ConvertProductName(string productName)
{
if (productName == "prod1")
return Product.Product1;
if (productName == "prod2")
return Product.Product2;
if (productName == "prod3")
return Product.Product3;
throw new ArgumentException("Unknown product: " + productName);
}

private static Fund ConvertFundName(string fundName)
{
if (fundName == "fund1")
return Fund.Fund1;
if (fundName == "fund2")
return Fund.Fund2;
if (fundName == "fund3")
return Fund.Fund3;
throw new ArgumentException("Unknown fund: " + fundName);
}

Simplification: The ConvertDict method can be rewritten using a single LINQ-expression like this:

private static Dictionary<T, double> ConvertDict<T>(
Dictionary<string, double> dict,
Func<string, T> convertKey)
{
return dict.ToDictionary(
kvp => convertKey(kvp.Key),
kvp => kvp.Value);
}

Simplification: And the convert methods would be nicer using a switch statement:

private static Product ConvertProductName(string productName)
{
switch (productName)
{
case "prod1": return Product.Product1;
case "prod2": return Product.Product2;
case "prod3": return Product.Product3;
default:
throw new ArgumentException("Unknown product: " + productName);
}
}

Then you call it this way:

    Dictionary<Product, double> prodDictA = ConvertDict<Product>(rawProdDictA, ConvertProductName);
Dictionary<Product, double> prodDictB = ConvertDict<Product>(rawProdDictB, ConvertProductName);
Dictionary<Fund, double> fundDictA = ConvertDict<Fund>(rawFundDictA, ConvertFundName);

Simplification: Or, you can even leave out the generic type and let the compiler figure out the <T> given the convertKey func you use:

    Dictionary<Product, double> prodDictA = ConvertDict(rawProdDictA, ConvertProductName);
Dictionary<Product, double> prodDictB = ConvertDict(rawProdDictB, ConvertProductName);
Dictionary<Fund, double> fundDictA = ConvertDict(rawFundDictA, ConvertFundName);

Convert Enum Collection to Dictionary Given Type

You can use generic method, which will create dictionary with enum values and names:

public static Dictionary<int, string> GetEnumList<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
throw new Exception("Type parameter should be of enum type");

return Enum.GetValues(enumType).Cast<int>()
.ToDictionary(v => v, v => Enum.GetName(enumType, v));
}

Feel free to modify default enum name as you need. Usage:

var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];

Enum to dictionary

Jon Skeet has written everything you need ;)

But here you have your code that is working:

public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
var type = @enum.GetType();
return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
}

create dictionary from enum names and display names

In this function, the Enum.GetValues call return a list of objects, which doesn't have a definition for GetDisplayName().

And the reason you see the same description for each one is that the @enum object is the only object you are using to get description

public static Dictionary<string, string> EnumDisplayNameDictionary<TEnum>(this Enum @enum)
{
var returnDict = new Dictionary<string, string>();
foreach (var item in Enum.GetValues(typeof(TEnum)))
{
returnDict.Add(item.ToString(), @enum.GetDisplayName());
}

return returnDict;
}

Simply cast item to Enum, and it will allow you to call GetDisplayName().

public static Dictionary<string, string> EnumDisplayNameDictionary<TEnum>(this Enum @enum)
{
var returnDict = new Dictionary<string, string>();
foreach (var item in Enum.GetValues(typeof(TEnum)))
{
returnDict.Add(item.ToString(), ((Enum)item).GetDisplayName());
}

return returnDict;
}

With this, the @enum object is not used within this function, so this could be changed to a static function, rather than an extension function.



Related Topics



Leave a reply



Submit