Tuesday, July 31, 2007

Get keys out of Hashtable

You've filled up your Hashtable with key/value pairs, now how do you get the keys out? Below is a simple way using foreach:

protected Hashtable list = new Hashtable();

public void AddItem(int itemnum, string title, int cost, int quantity)
{
  Item i = new Item();
  i.Cost=cost;
  i.ItemId=itemnum;
  i.Quantity=quantity;
  i.Title=title;

  list.Add(itemnum, i);
}

public int GetTotal()
{
  int tot=0;
   IDictionaryEnumerator Enum = list.GetEnumerator();
  while(Enum.MoveNext())
{
     Item i = (Item)list[Enum.Key];
    tot+=(i.Cost*i.Quantity);
}

  return tot;
}

No comments: