Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best data structure in .NET for look-up by string key or numeric index?

I'm looking for the most ideal data structure (for performance and ease of use) from which values can be retrieved by string key or index. Dictionary doesn't work because you can't really retrieve by index. Any ideas?

like image 325
JC Grubbs Avatar asked Sep 26 '08 04:09

JC Grubbs


People also ask

Which data structure is best for lookup?

What is the most efficient data structure for this? Looking at complexity analysis, Hashtables seem to be the most efficient for lookups.

In which data structure lookup is fast?

A heap will only let you search quickly for the minimum element (find it in O(1) time, remove it in O(log n) time). If you design it the other way, it will let you find the maximum, but you don't get both. To search for arbitrary elements quickly (in O(log n) time), you'll want the binary search tree. Good answer.

What is the best data structure which can be used to store the collection of strings?

Trie. A trie, also known as a keyword tree, is a data structure that stores strings as data items that can be organized in a visual graph.


2 Answers

You want the OrderedDictionary class. You will need to include the System.Collections.Specialized namespace:

    OrderedDictionary od = new OrderedDictionary(); 
    od.Add("abc", 1); 
    od.Add("def", 2); 
    od.Add("ghi", 3); 
    od.Add("jkl", 4); 

    // Can access via index or key value:      
    Console.WriteLine(od[1]);       
    Console.WriteLine(od["def"]);
like image 144
Mitch Wheat Avatar answered Sep 21 '22 10:09

Mitch Wheat


There's System.Collections.ObjectModel.KeyedCollection< string,TItem>, which derives from Collection< TItem>. Retrieval is O(1).

class IndexableDictionary<TItem> : KeyedCollection<string, TItem>
 { Dictionary<TItem, string> keys = new Dictionary<TItem, string>();

   protected override string GetKeyForItem(TItem item) { return keys[item];}

   public void Add(string key, TItem item) 
    { keys[item] = key;
      this.Add(item);
    }
 }
like image 37
Mark Cidade Avatar answered Sep 22 '22 10:09

Mark Cidade