Dictionary<String, UInt32> dict = new Dictionary<String, UInt32>();
dict.Add("1", 1);
dict.Add("4", 4);
dict.Add("5", 5);
将所有键转换为数组的快速方法是
string[] keys = dict.Keys.ToArray();
这就是数组的内存表示形式
keys [0] =“1”键[1] =“4”键[2] =“5”
我想要的是,键字符串值应该在由value指定的索引处的数组中.
keys[1] = "1" keys[4] = "4" keys[5] = "5"
这是我试过的,它的工作原理..
Int32 count = -1;
foreach (KeyValuePair<String, UInt32> kvp in dict)
{
if (kvp.Value > count)
{
count = (Int32)kvp.Value;
}
}
String[] labelarray = new String[count + 1];
foreach (KeyValuePair<String, UInt32> kvp in dict)
{
labelarray[kvp.Value] = kvp.Key;
}
但是,上面有更好,更清洁的方法吗?
最佳答案 您可以使用
Enumerable.ToDictionary
还原键和值.
var revertedDictionary = list.ToDictionary(x => x.Value, x => x.Key);
List< T>的另一种方式或数组有两部分:搜索最大索引和填充集合:
if(!list.Any())
{
// use different behavior if you need
return new string[0];
}
var maxValue = list.Values.Max();
var newList = new string[maxValue];
Enumerable
.Range(0, (int)maxValue)
.ToList()
.ForEach(x => newList[x] = list.ContainsValue((uint)x) ? x.ToString() : string.Empty);
// improve memory usage by preventing to create new List in ToList() method
foreach(var index in Enumerable.Range(0, (int)maxValue))
{
newList[index] = list.ContainsValue((uint)index) ? index.ToString() : string.Empty;
}