8
public static Hashtable Drinks = new Hashtable();
Drinks["Water"] = 3;
Drinks["Coffee"] = 2
Drinks["Beer"] = 5;

To get the value of item I use: int drink = (int)Drinks["Water"]; which works.

I wanted to know how i can make this work. pCardValue1 = (int)card[1];

Like instead of typing the item name i want to get the value by position.

  • You can use Linq to convert your Hashtable into, say List and then get required item; but Hashtable is not a good collection to be addressed like that – Dmitry Bychenko Feb 06 '14 at 12:18
  • Do you need a possibility to find element (key and value) by index or do you want to be able: a) to find value by key b) key by value? Second option is not existing by default I think, you have to implement it, by having something simple with slow search (`List` and linq to search) or with even slower insert (two `Hashtable`, where one is key-value and second is value-key, only possible if you do not allow duplicates for values). Also check [this](http://stackoverflow.com/questions/1171812/multi-key-dictionary-in-c). – Sinatr Feb 06 '14 at 12:44

4 Answers4

4

The Hashtable (and Dictionary) class is not ordered, meaning, it's entries don't have any order or position, and even if you get a list of keys, the order is random. If you want to get values by key and position as well, you should use the OrderedDictionary collection.

fejesjoco
  • 11,763
  • 3
  • 35
  • 65
4

You need a OrderedDictionary. HashTable is not ordered.

Also note that HashTable should not be used in production code from framework 2.0, there is a Dictionary<TKey,TValue> class in System.Collections.Generic namespace which is a replacement for HashTable and provides generics.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
3

As already mentioned, you should use OrderedDictionary. Since you asked for an example in the comments, here is one:

var stringKey = "stringKey";
            var stringValue = "stringValue";

            var objectKey = "dateTimeKey";
            var objectValue = DateTime.Now;

            var dict = new OrderedDictionary();
            dict.Add(stringKey, stringValue);
            dict.Add(objectKey, objectValue);

            for (int i = 0; i < dict.Count; i++)
            {
                var value = dict[i];
            }

Enumerating the dictionary several times will return the results in the same order. Note that since it accepts an Object for both key and value, you can mix different types as much as you want, meaning you have to be careful when you use the structure.

PetarPenev
  • 339
  • 3
  • 7
0

you can use linq trick to get item name at position.

int position = 1;
var a1 = (from DictionaryEntry entry in Drinks select entry.Key).Skip(position).FirstOrDefault();

If you want item name by value then use

object value = 2;
var a = (from DictionaryEntry entry in Drinks where entry.Value.Equals(value) select entry.Key).FirstOrDefault();
Sameer
  • 2,143
  • 1
  • 16
  • 22