如何将Enum转换为Key,Value Pairs.我已经用C#3.0转换了它.
public enum Translation
{
English,
Russian,
French,
German
}
string[] trans = Enum.GetNames(typeof(Translation));
var v = trans.Select((value, key) =>
new { value, key }).ToDictionary(x => x.key + 1, x => x.value);
Run Code Online (Sandbox Code Playgroud)
在C#1.0中,这样做的方法是什么?
小智 18
对于C#3.0,如果你有这样的枚举:
public enum Translation
{
English = 1,
Russian = 2,
French = 4,
German = 5
}
Run Code Online (Sandbox Code Playgroud)
不要使用这个:
string[] trans = Enum.GetNames(typeof(Translation));
var v = trans.Select((value, key) =>
new { value, key }).ToDictionary(x => x.key + 1, x => x.value);
Run Code Online (Sandbox Code Playgroud)
因为它会弄乱你的密钥(这是一个整数).
相反,使用这样的东西:
var dict = new Dictionary<int, string>();
foreach (var name in Enum.GetNames(typeof(Translation)))
{
dict.Add((int)Enum.Parse(typeof(Translation), name), name);
}
Run Code Online (Sandbox Code Playgroud)
我想,这个例子会对你有所帮助。
例如,您的枚举定义如下:
public enum Translation
{
English,
Russian,
French,
German
}
Run Code Online (Sandbox Code Playgroud)
您可以使用下面的代码片段将 enum 转换为KeyValuePairs:
var translationKeyValuePairs = Enum.GetValues(typeof(Translation))
.Cast<int>()
.Select(x => new KeyValuePair<int, string>(key: x, value: Enum.GetName(typeof(Translation), x)))
.ToList();
Run Code Online (Sandbox Code Playgroud)
或者您可以使用字典,如下所示:
var translationDictionary = Enum.GetValues(typeof(Translation))
.Cast<int>()
.ToDictionary(enumValue => enumValue,
enumValue => Enum.GetName(typeof(Translation), enumValue));
Run Code Online (Sandbox Code Playgroud)
注意:如果您的枚举类型不是int,例如枚举类型是byte,您可以Cast<byte>()使用Cast<int>()
在C#1 ......
string[] names = Enum.GetNames(typeof(Translation));
Hashtable hashTable = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
hashTable[i + 1] = names[i];
}
Run Code Online (Sandbox Code Playgroud)
你确定你真的想要一个从索引到名字的地图吗?如果您只是使用整数索引,为什么不使用数组或ArrayList?