Getting index of dictionary item based on item.key

There is no concept of an index in a Dictionary. You can't rely on any order of items inside the Dictionary. The OrderedDictionary might be an alternative.

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

This might work and this is probably not the most efficient way of doing this. Also im not sure why you would want something like this.

Int termIndex = Array.IndexOf(myDictionary.Keys.ToArray(), someKey);

There is no way to get index, since data storing in memory in absolutely different ways for array and dictionary.

When you declare array of any type, you know, that data will be placed in memory cells one after the other. So, index is a shift of memory address.

When you put data in a dictionary, you can't predict the address, that will be used for this item, because it will be placed in specific empty position, which will provide balanced graph for fast search by key. So, you can't manipulate with dictionary data using index.

P.S. I believe, that you can resolve your problem using Linq.

Tags:

C#