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)
另一种基于Arithmomaniac 示例的扩展方法:
/// <summary>
/// Returns a Dictionary<int, string> 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)
ArgumentException
如果类型不是System.Enum
,则抛出一个,谢谢Enum.GetValues
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)