Link to home
Create AccountLog in
Avatar of kalyangkm
kalyangkmFlag for United States of America

asked on

How to add and retrieve the data with key value pair without using dictionary

How to add and retrieve the data with key value pair without using dictionary?
Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa image

Why would you want to do that?

You can however replicate this with a 2 dimensional array, or List of POCO objects. Doing that is like reinventing the wheel though.
Hi,
You can use Tuples, but this data structure is not "aware" about a key-value thing.
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
You can try Indexer  [c#].
if using first sample posted by saige, you would add key-value pair by

Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
myDictionary[key].Add(new string(value));

Open in new window


to retrieve key-value pairs by key do

List<string> valueList;
if (myDictionary.TryGetValue(key, out valueList))
{ 
     for each (string value in valueList)
     {
            ...
     }
}

Open in new window



How to add and retrieve the data with key value pair without using dictionary?

you could use a list of key-value pairs like saige has described, or if the key is part of the value class you could use a list of values, or you use a list of separate class containing key and value as members. after adding items to the list, sort the list by key.

the sort statement is like

List<KeyValue> myList;    // assume KeyValue has members key and value
....
myList.Sort((kv1, kv2) => kv1.key.CompareTo(f2.key));

Open in new window


to retrieve key-value pairs from list by key you either could search sequentially until you find the key. this is not elegant but for small lists - say count < 100 - the difference in speed is not measurable. if the list is sorted you could stop at the first catch and get all values to the same key by checking the next items of the list. so you would look-up about half time compared to searching the unsorted list. if sorted, however you could do a binary search like that:

    
    int start = 0; 
    int end   = myList.Count;
    int result  = 0;
    while (start < end)
    {
        int mid = (start + end) / 2;
        result = key.CompareTo(myList[mid].key));
        if (result <= 0)
        {
           end = mid;
        }
        else
        {
           start = mid + 1;
        }
    }
    if (result == 0)
    {  
          // first key-value pair found at index start 

          // check next keys from start + 1 whether there are more key-value pairs containing the same key
    }

Open in new window


what of course is reinventing the wheel but nevertheless a nice little piece of code.

Sara