Ich habe dies online gesucht, finde aber nicht die Antwort, die ich suche. Grundsätzlich habe ich folgende Aufzählung:
public enum typFoo : int
{
itemA : 1,
itemB : 2
itemC : 3
}
Wie kann ich dieses Enum in Dictionary konvertieren, damit es im folgenden Dictionary gespeichert wird
Dictionary<int,string> mydic = new Dictionary<int,string>();
und mydic würde so aussehen:
1, itemA
2, itemB
3, itemC
Irgendwelche Ideen?
siehe: Wie zähle ich eine Aufzählung auf?
foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
mydic.Add((int)foo, foo.ToString());
}
Versuchen:
var dict = Enum.GetValues(typeof(typFoo))
.Cast<typFoo>()
.ToDictionary(t => (int)t, t => t.ToString() );
Anpassung von Anis Antwort damit sie als generische Methode verwendet werden kann (Danke, 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
aus, wenn der Typ nicht System.Enum
ist, dank Enum.GetValues
enum
-Einschränkung verfügbar)public static Dictionary<T, string> ToDictionary<T>() where T : struct
=> Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
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;
}
}
Verwendungszweck :
public enum typFoo : int
{
itemA = 1,
itemB = 2,
itemC = 3
}
var mydic = EnumHelper.ConvertToDictionary<typFoo>();
Hier ist die VB.NET-Version von Anis Antwort:
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 meinem Fall wollte ich den Pfad wichtiger Verzeichnisse speichern und im AppSettings-Abschnitt meiner web.config speichern. Dann habe ich ein Enum erstellt, um die Schlüssel für diese AppSettings darzustellen ... aber mein Front-End-Techniker benötigte Zugriff auf diese Speicherorte in unseren externen Javascript-Dateien. Also habe ich den folgenden Codeblock erstellt und in unsere primäre Masterseite eingefügt. Jetzt erstellt jedes neue Enum-Element automatisch eine entsprechende Javascript-Variable. Hier ist mein Codeblock:
<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>
HINWEIS: In diesem Beispiel habe ich den Namen der Aufzählung als Schlüssel verwendet (nicht den int-Wert).
Sie können über die Aufzählungsbeschreibungen auflisten:
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);
}
Dies sollte den Wert jedes Elements und den Namen in Ihr Wörterbuch aufnehmen.
Eine weitere Erweiterungsmethode, die auf dem obigen Beispiel von Arithmomaniacs aufbaut.
/// <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());
}
Reflexion verwenden:
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);
}
Wenn Sie nur den Namen benötigen, müssen Sie das Wörterbuch überhaupt nicht erstellen.
Das wird enum in int konvertieren:
int pos = (int)typFoo.itemA;
Dies wird int in enum konvertieren:
typFoo foo = (typFoo) 1;
Und dies wird Ihnen den Namen zurückgeben:
((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;
}
}