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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13489771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:45:12  来源:igfitidea点击:

Getting index of dictionary item based on item.key

c#

提问by FSm

How can I find the index of an element of a dictionary based on the element key? I'm using the following code to go through the dictionary:

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

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

Could anyone help please?

有人可以帮忙吗?

采纳答案by Dennis Traub

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

中没有索引的概念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;
}

回答by Richard

As Dennis states there is no index in dictionary but in your example the position in the foreach loop could be tracked as so:

正如丹尼斯所说,字典中没有索引,但在您的示例中,可以这样跟踪 foreach 循环中的位置:

int index = -1;
foreach (var entry in freq)
            {

                var word = entry.Key;
                var wordFreq = entry.Value;
                int termIndex = ++index;


            }

回答by Warlock

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.

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

回答by rasputino

Maybe something like this could work:

也许这样的事情可以工作:

public static int GetIndex(Dictionary<string, object> dictionary, string key) 
{
    for (int index = 0; index < dictionary.Count; index++)
    {
        if(dictionary.Skip(index).First().Key == key)
            return index;
    }

    return -1;
}

Based on Dennis Traub solution, but using a Dictionary... (it's orderer by the original addition)

基于 Dennis Traub 解决方案,但使用字典......(它是原始添加的排序器)

回答by Vakun

There is 2 extension methods

有2种扩展方法

Index by key

按键索引

public static int IndexOf<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) 
    {
        int i = 0;
        foreach(var pair in dictionary)
        {
            if(pair.Key.Equals(key))
            {
                return i;
            }
            i++;
        }
        return -1;
    }

Index by value

按值索引

public static int IndexOf<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TValue value) 
    {
        int i = 0;
        foreach(var pair in dictionary)
        {
            if(pair.Value.Equals(value))
            {
                return i;
            }
            i++;
        }
        return -1;
    }

回答by Raiven66

It's old but someone might use it - I currently use

它很旧但有人可能会使用它 - 我目前使用

public static int OrderedDictIndexOfKey(string key, OrderedDictionary oDict)
{
    int i = 0;
    foreach (DictionaryEntry oDictEntry in oDict)
    {
        if ((string)oDictEntry.Key == key) return i;
        i++;
    }

    return -1;
}

public static object OrderedDictKeyAtIndex(int index, OrderedDictionary oDict)
{
    if (index < oDict.Count && index >= 0)
    {
        return oDict.Cast<DictionaryEntry>().ElementAt(index).Key;
    }
    else
    {
        return null;
    }
}

回答by dylful

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

回答by Ondrej Rozinek

The dictionary implementation in .NET hashtable has no defined index because it is based on a hash key. I find the answers here to be inefficient and slow because many of these solutions do not preserve the time complexity of the O (1) Dictionary data structure. The ordered dictionary has some performance disadvantages compared to the dictionary.

.NET 哈希表中的字典实现没有定义索引,因为它基于哈希键。我发现这里的答案效率低下且速度缓慢,因为其中许多解决方案都没有保留 O(1) 字典数据结构的时间复杂度。与字典相比,有序字典有一些性能上的劣势。

The only once efficient possible solution is to add an index while building the dictionary. So you should have e.g.

唯一一次有效的可能解决方案是在构建字典时添加索引。所以你应该有例如

Dictionary<string, Tuple <int, int >>

where in the tuple you would add an index if you add a new key-value pair. This simple solution preserves the time O (1) and in addition you can have a property with an index.

如果您添加新的键值对,您将在元组中的何处添加索引。这个简单的解决方案保留了时间 O (1),此外您还可以拥有一个带有索引的属性。