根据item.key获取字典项的索引

FSm*_*FSm 12 c#

如何根据元素键找到字典元素的索引?我正在使用以下代码来浏览字典:

foreach (var entry in freq)
{
    var word = entry.Key;
    var wordFreq = entry.Value;
    int termIndex = ??????;
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

Den*_*aub 10

a中没有索引的概念Dictionary.你不能依赖于里面任何物品的顺序Dictionary.将OrderedDictionary可能是一个选择.

var freq = new OrderedDictionary<string, int>();
// ...

foreach (var entry in freq)
{
    var word = entry.Key;
    var wordFreq = entry.Value;
    int termIndex = GetIndex(freq, entry.Key);
}


public int GetIndex(OrderedDictionary<string, object> dictionary, string key) 
{
    for (int index = 0; index < dictionary.Count; index++)
    {
        if (dictionary.Item[index] == dictionary.Item[key]) 
            return index; // We found the item
    }

    return -1;
}
Run Code Online (Sandbox Code Playgroud)


War*_*ock 6

没有办法获得索引,因为数据以完全不同的方式存储在内存中用于数组和字典.

当您声明任何类型的数组时,您知道,该数据将一个接一个地放入存储器单元中.所以,索引是内存地址的转移.

当您将数据放入字典时,您无法预测将用于此项目的地址,因为它将被放置在特定的空位置,这将为按键快速搜索提供平衡图形.因此,您无法使用索引操作字典数据.

PS我相信,您可以使用Linq解决您的问题.


dyl*_*ful 5

这可能有效,并且这可能不是最有效的方法。我也不确定为什么要这样的事情。

Int termIndex = Array.IndexOf(myDictionary.Keys.ToArray(), someKey);
Run Code Online (Sandbox Code Playgroud)