1

can anyone tell me how I can search a hash table for a specific key and put off the corresponding value in a variable (e.g. Both key and value are from the class point)

I add the values as followed:

Hashtable Hash = new Hashtable();     
Hash.Add(new Point(Po.X - 1, Po.Y), new Point(Po.X, Po.Y));
LoNy
  • 25
  • 4

2 Answers2

2

You can use the following:

Point value;
if (Hash.ContainsKey(YourKey))
{
    value = (Point)Hash[YourKey];
}
nevets
  • 4,631
  • 24
  • 40
2

Instead of HashTable you should look at generic Dictionary<T,T>. (if you are using .Net framework 2.0 or higher)

But if you want to get the key from current non generic HashTable you can do:

var KeyToSearch = new Point(10 - 1, 20);
if (Hash.ContainsKey(KeyToSearch))
{
    var value = Hash[KeyToSearch];
}

But remember, value is of type object, and you have to use explicit cast to get Point object back like:

Point value = (Point) Hash[KeyToSearch] ;

If you were to use Dictionary<Point,Point>, then you can achieve the same thing without casting.

One more thing to add, Point here is considered a struct from System.Drawing, If it is a class then ContainsKey and accessing based on Key would compare the reference and not the actual values. If your Point is a class (a reference type) then you have to override GetHashCode and Equals You may see this answer for more details.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436