如何将字典键转换为字符串数组(在字典中指定的数组索引处插入)

本文关键字:字典 数组 插入 索引 转换 字符串 | 更新日期: 2023-09-27 18:34:46

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" keys[1] = "4" keys[2] = "5"

我想要的是,键字符串值应该在由值指定的索引处的数组中。

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>Array的方法有两部分:搜索最大索引和填充集合:

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;
}