[英]Enum to Dictionary in C#
I have searched this online, but I can't find the answer I am looking for.我在网上搜索过这个,但找不到我要找的答案。
Basically I have the following enum:基本上我有以下枚举:
public enum typFoo : int
{
itemA : 1,
itemB : 2
itemC : 3
}
How can I convert this enum to Dictionary so that it stores in the following Dictionary?如何将此枚举转换为 Dictionary 以便它存储在以下 Dictionary 中?
Dictionary<int,string> myDic = new Dictionary<int,string>();
And myDic would look like this: myDic 看起来像这样:
1, itemA
2, itemB
3, itemC
Any ideas?有任何想法吗?
Try:尝试:
var dict = Enum.GetValues(typeof(fooEnumType))
.Cast<fooEnumType>()
.ToDictionary(t => (int)t, t => t.ToString() );
See: How do I enumerate an enum in C#?请参阅: 如何在 C# 中枚举枚举?
foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
mydic.Add((int)foo, foo.ToString());
}
Adapting Ani's answer so that it can be used as a generic method (thanks, toddmo ):改编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());
}
ArgumentException
if the type is not System.Enum
, thanks to Enum.GetValues
如果类型不是System.Enum
,则抛出ArgumentException
,感谢Enum.GetValues
enum
constraint is available yet) IntelliSense 将仅限于结构(尚无enum
约束可用)public static Dictionary<T, string> ToDictionary<T>() where T : struct
=> Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
Another extension method that builds on Arithmomaniac's example :另一种基于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.Ordianal).</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());
}
Here's the VB.NET version of Ani's answer:这是 Ani 回答的 VB.NET 版本:
Public Enum typFoo
itemA = 1
itemB = 2
itemC = 3
End Enum
Sub example()
Dim dict As Dictionary(Of Integer, String) = System.Enum.GetValues(GetType(typFoo)) _
.Cast(Of typFoo)() _
.ToDictionary(Function(t) Integer.Parse(t), Function(t) t.ToString())
For Each i As KeyValuePair(Of Integer, String) In dict
MsgBox(String.Format("Key: {0}, Value: {1}", i.Key, i.Value))
Next
End Sub
In my case, I wanted to save the path of important directories and store them in my web.config
file's AppSettings section.就我而言,我想保存重要目录的路径并将它们存储在我的web.config
文件的 AppSettings 部分中。 Then I created an enum to represent the keys for these AppSettings...but my front-end engineer needed access to these locations in our external JavaScript files.然后我创建了一个枚举来表示这些 AppSettings 的键……但是我的前端工程师需要访问我们外部 JavaScript 文件中的这些位置。 So, I created the following code-block and placed it in our primary master page.因此,我创建了以下代码块并将其放置在我们的主母版页中。 Now, each new Enum item will auto-create a corresponding JavaScript variable.现在,每个新的 Enum 项都会自动创建一个相应的 JavaScript 变量。 Here's my code block:这是我的代码块:
<script type="text/javascript">
var rootDirectory = '<%= ResolveUrl("~/")%>';
// This next part will loop through the public enumeration of App_Directory and create a corresponding JavaScript variable that contains the directory URL from the web.config.
<% Dim App_Directories As Dictionary(Of String, App_Directory) = System.Enum.GetValues(GetType(App_Directory)) _
.Cast(Of App_Directory)() _
.ToDictionary(Of String)(Function(dir) dir.ToString)%>
<% For Each i As KeyValuePair(Of String, App_Directory) In App_Directories%>
<% Response.Write(String.Format("var {0} = '{1}';", i.Key, ResolveUrl(ConfigurationManager.AppSettings(i.Value))))%>
<% next i %>
</script>
NOTE: In this example, I used the name of the enum as the key (not the int value).注意:在这个例子中,我使用枚举的名称作为键(不是 int 值)。
You can enumerate over the enum descriptors:您可以枚举枚举描述符:
Dictionary<int, string> enumDictionary = new Dictionary<int, string>();
foreach(var name in Enum.GetNames(typeof(typFoo))
{
enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)), name), name);
}
That should put the value of each item and the name into your dictionary.这应该将每个项目的值和名称放入您的字典中。
Use:采用:
public static class EnumHelper
{
public static IDictionary<int, string> ConvertToDictionary<T>() where T : struct
{
var dictionary = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (var value in values)
{
int key = (int) value;
dictionary.Add(key, value.ToString());
}
return dictionary;
}
}
Usage:用法:
public enum typFoo : int
{
itemA = 1,
itemB = 2,
itemC = 3
}
var mydic = EnumHelper.ConvertToDictionary<typFoo>();
Using reflection:使用反射:
Dictionary<int,string> mydic = new Dictionary<int,string>();
foreach (FieldInfo fi in typeof(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static))
{
mydic.Add(fi.GetRawConstantValue(), fi.Name);
}
If you need only the name you don't have to create that dictionary at all.如果您只需要名称,则根本不必创建该字典。
This will convert enum to int:这会将枚举转换为 int:
int pos = (int)typFoo.itemA;
This will convert int to enum:这会将 int 转换为 enum:
typFoo foo = (typFoo) 1;
And this will retrun you the name of it:这将返回它的名称:
((typFoo) i).toString();
public class EnumUtility
{
public static string GetDisplayText<T>(T enumMember)
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("Requires enum only");
var a = enumMember
.GetType()
.GetField(enumMember.ToString())
.GetCustomAttribute<DisplayTextAttribute>();
return a == null ? enumMember.ToString() : a.Text;
}
public static Dictionary<int, string> ParseToDictionary<T>()
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("Requires enum only");
Dictionary<int, string> dict = new Dictionary<int, string>();
T _enum = default(T);
foreach(var f in _enum.GetType().GetFields())
{
if(f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
dict.Add((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text);
}
return dict;
}
public static List<(int Value, string DisplayText)> ParseToTupleList<T>()
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("Requires enum only");
List<(int, string)> tupleList = new List<(int, string)>();
T _enum = default(T);
foreach (var f in _enum.GetType().GetFields())
{
if (f.GetCustomAttribute<DisplayTextAttribute>() is DisplayTextAttribute i)
tupleList.Add(((int)f.GetValue(_enum), i == null ? f.ToString() : i.Text));
}
return tupleList;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.