枚举到字典c#

dae*_*aai 56 c# collections enums dictionary

我在网上搜索但无法找到我要找的答案.基本上我有以下枚举:

public enum typFoo : int
{
   itemA : 1,
   itemB : 2
   itemC : 3
}
Run Code Online (Sandbox Code Playgroud)

如何将此枚举转换为Dictionary,以便它存储在以下字典中

Dictionary<int,string> mydic = new Dictionary<int,string>();
Run Code Online (Sandbox Code Playgroud)

和mydic看起来像这样:

1, itemA
2, itemB
3, itemC
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Ani*_*Ani 147

尝试:

var dict = Enum.GetValues(typeof(typFoo))
               .Cast<typFoo>()
               .ToDictionary(t => (int)t, t => t.ToString() );
Run Code Online (Sandbox Code Playgroud)


Zha*_*ais 48

请参阅:如何枚举枚举?

foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
    mydic.Add((int)foo, foo.ToString());
}
Run Code Online (Sandbox Code Playgroud)


Ari*_*iac 14

调整Ani的答案,以便它可以用作通用方法(谢谢,toddmo):

public static Dictionary<int, string> EnumDictionary<T>()
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("Type must be an enum");
    return Enum.GetValues(typeof(T))
        .Cast<T>()
        .ToDictionary(t => (int)(object)t, t => t.ToString());
}
Run Code Online (Sandbox Code Playgroud)

  • 你能做`(int)(object)t`而不是`(int)Convert.ChangeType(t,t.GetType())`吗?它编译。`ChangeType`返回一个`object`,所以我认为您的装箱方式都是这样。 (2认同)

j2a*_*tes 6

另一种基于Arithmomaniac 示例的扩展方法:

    /// <summary>
    /// Returns a Dictionary&lt;int, string&gt; of the parent enumeration. Note that the extension method must
    /// be called with one of the enumeration values, it does not matter which one is used.
    /// Sample call: var myDictionary = StringComparison.Ordinal.ToDictionary().
    /// </summary>
    /// <param name="enumValue">An enumeration value (e.g. StringComparison.Ordinal).</param>
    /// <returns>Dictionary with Key = enumeration numbers and Value = associated text.</returns>
    public static Dictionary<int, string> ToDictionary(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        return Enum.GetValues(enumType)
            .Cast<Enum>()
            .ToDictionary(t => (int)(object)t, t => t.ToString());
    }
Run Code Online (Sandbox Code Playgroud)


tod*_*dmo 5

  • 扩展方法
  • 常规命名
  • 一条线
  • c#7返回语法(但你可以在那些旧版本的c#中使用括号)
  • ArgumentException如果类型不是System.Enum,则抛出一个,谢谢Enum.GetValues
  • Intellisense将仅限于结构(尚无enum约束)
  • 如果需要,允许您使用枚举索引到字典中.
public static Dictionary<T, string> ToDictionary<T>() where T : struct
  => Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
Run Code Online (Sandbox Code Playgroud)