locked
How to get the index of the Dictionary key ? RRS feed

  • คำถาม

  • Is it possible to get the index of a specific Dictionary key? e.g. something like this:

    Dictionary myDictionary = new Dictionary<string, string >;
    myDictionary.Add("a","x");
    myDictionary.Add("b","y");
    int i;
    i = GetIndexOfKey (myDictionary, "a"); //should return 0 or 1
    i = GetIndexOfKey (myDictionary, "b"); //should return 0 or 1

    It should return either 0 or 1 in each of the above case, because there are 2 elements in the dictionary.
    13 มีนาคม 2553 7:15

คำตอบ

  • > Is it possible to get the index of a specific Dictionary key?

    It is possible (see Omie's code), but if your program needs this for anything other than some diagnostic purpose, there might be something significantly wrong with your design!

    The entries of Dictionary<K,V> are not intended to be accessed by index, so the Dictionary<K,V> does not provide any method to do what you stated efficiently.  (That is, you need to do a O(N) loop over the Dictionary to do it yourself.  There is no O(1) method.)  Furthermore, as soon as you perform any Add or Remove to the Dictionary, any indexes obtained prior might be invalid.  Which ones are invalid depends on the hash code of what you added or removed in conjunction with the details of the hash table's internal algorithms.

    • ทำเครื่องหมายเป็นคำตอบโดย monetia 13 มีนาคม 2553 16:48
    13 มีนาคม 2553 15:35

ตอบทั้งหมด

  • Something like this ?

            Dictionary<String,String> dict = new Dictionary<String, String>();
    
            private void Form1_Load(object sender, EventArgs e)
            {
                dict.Add("One","Omie");
                dict.Add("Two","MSDN");
                dict.Add("Three", "Microsoft");            
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                MessageBox.Show(getIndexOfKey(dict,"Three").ToString());
            }
    
            private int getIndexOfKey(Dictionary<string,string> tempDict,String key)
            {
                int index = -1;
                foreach (String value in tempDict.Keys)
                {
                    index++;
                    if (key == value)
                        return index;
    	        }
                return -1;
            }

    Thanks

    Real Programmers don't comment their code. If it was hard to write, it should be hard to understand.
    My BlogMy Facebook
    13 มีนาคม 2553 7:56
  • or something like this:
      Private Sub ToTry()
        Dim dict As New Dictionary(Of String, String)
        dict.Add("One", "Omie")
        dict.Add("Two", "MSDN")
        dict.Add("Three", "Microsoft")
    
        Dim theIndexOfThree As Integer = GetIndexOfKey(dict, "Three")
      End Sub
    
      Private Function GetIndexOfKey(ByVal dict As Dictionary(Of String, String), _
                                     ByVal key As String) As Integer
        Dim keys(dict.Count - 1) As String
        dict.Keys.CopyTo(keys, 0)
        Return Array.IndexOf(keys, key)
      End Function

    please, mark this as answer if it is THE answer
    ----------------
    Diego Cattaruzza
    Microsoft MVP - Visual Basic: Development
    blog: http://community.visual-basic.it/Diego
    web site: http://www.visual-basic.it
    13 มีนาคม 2553 10:34
  •       Dictionary<stringstring> myDictionary = new Dictionary<stringstring>();
          myDictionary.Add(
    "a""x");
          myDictionary.Add(
    "b""y");
          
    int i = Array.IndexOf(myDictionary.Keys.ToArray(), "a");
          
    int j = Array.IndexOf(myDictionary.Keys.ToArray(), "b");

    • ทำเครื่องหมายเป็นคำตอบโดย monetia 13 มีนาคม 2553 16:49
    • ยกเลิกการทำเครื่องหมายเป็นคำตอบโดย monetia 13 มีนาคม 2553 16:50
    13 มีนาคม 2553 11:39
  • hee hee hee
    Thanks

    Real Programmers don't comment their code. If it was hard to write, it should be hard to understand.
    My BlogMy Facebook
    13 มีนาคม 2553 13:43
  • A Dictionary item doesn't have an index. They are not indexable and the order you add items is not preserved. If you need indexing you have to use a different container. If you need both fast lookup (by key) and indexing you need two containers.
    • แก้ไขโดย Tergiver 13 มีนาคม 2553 15:11
    13 มีนาคม 2553 14:55
  • After I said that I wrote a little proof and found it wasn't true. A Dictionary is a hash table, it should be true, so why isn't it? Because Dictionary stores way more information than it needs (it's a bit of a pig now that I've seen it up close). It stores keys and values in two separate lists and uses the hash table to index those lists.

    So it is in fact "indexable".
    13 มีนาคม 2553 15:11
  • > Is it possible to get the index of a specific Dictionary key?

    It is possible (see Omie's code), but if your program needs this for anything other than some diagnostic purpose, there might be something significantly wrong with your design!

    The entries of Dictionary<K,V> are not intended to be accessed by index, so the Dictionary<K,V> does not provide any method to do what you stated efficiently.  (That is, you need to do a O(N) loop over the Dictionary to do it yourself.  There is no O(1) method.)  Furthermore, as soon as you perform any Add or Remove to the Dictionary, any indexes obtained prior might be invalid.  Which ones are invalid depends on the hash code of what you added or removed in conjunction with the details of the hash table's internal algorithms.

    • ทำเครื่องหมายเป็นคำตอบโดย monetia 13 มีนาคม 2553 16:48
    13 มีนาคม 2553 15:35
  • Furthermore, as soon as you perform any Add or Remove to the Dictionary, any indexes obtained prior might be invalid.
    Right! I forgot about removal. That will definately skew your indices.
    13 มีนาคม 2553 16:22
  • I was in fact looking for some trick to retrieve the index of the dictionary in O(1) (without copying to array each time, because it is costly operation). If it is not possible, then I'll write a separate array, thanks a lot for fast answers!
    13 มีนาคม 2553 16:53
  • or,

    return tempDict.Keys.ToList.IndexOf(value)

    12 ธันวาคม 2562 13:57