0

I am on search for a datastucture that allows me to search for keys and values also. Quite now I´m using a simple dictionary for that, but if I search for values within it I have to loop all keys (having O(n) if I´m right). But since my map is quite small (having just 5 entries) I´m not sure if this would matter anyway.

Dictionary<string, int> myDict = new Dictionary<string, int> {
    {"first", 1},
    {"second", 2},
    {"third", 3},
    {"fourth", 4},
    {"fifth", 5}
}

Now accessing the map by key is easy:

var myInt = myDict["second"]; // O(1)

But because I need to access this map quite often (for keys and values) I´m not sure if there is a better way to store the values then this:

var myString = myDict.Single(x => x.Value == 2).Key; // O(n)
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

2 Answers2

2

From discussion we learned that your values are unique too, so you could keep two maps:

Dictionary<string, int> myDict = new Dictionary<string, int> {
    {"first", 1},
    {"second", 2},
    {"third", 3},
    {"fourth", 4},
    {"fifth", 5}
}

Dictionary<int, string> myReverseDict = new Dictionary<int, string {
    {1, "first"},
    {2, "second"},
    {3, "third"},
    {4, "fourth"},
    {5, "fifth"}
}

If the dictionary data changes during runtime, you should write a method to synchronize the two dictionaries.

This approach is simple, fast and versatile BUT there is an overhead when data changes.

helb
  • 7,609
  • 8
  • 36
  • 58
0

Consider an enum (if your list is always the same):

enum MyDic
{
  First = 1,
  Second,
  Third,
  Fourth,
  Fifth
}

This makes easy both "get Value by Key" and "get Value by Key":

var stringResult = (MyDic) 1; // returns First, use ToString() to get "First" as text.
var numResult = (int) MyDic.First; // returns 1

Check this out:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(((MyDic)1).ToString());
            Console.WriteLine((int)MyDic.First);
            Console.ReadKey();
        }
    }    

Note: it's possible to overcomplicate your enum using Description Attribute to describe with a different text your value:

 enum MyDic
 {
      [Description("Uno")]
      First = 1,
      Second,
      Third,
      Fourth,
      Fifth
 }

but the way to retrieve the value is way longer than the simple one (remember the KISS principle)

Francesco De Lisi
  • 1,493
  • 8
  • 20