Hashtable fails miserably.. i not sure why this cannot work???

G

Guest

Hi i very wonder, why i can't get the right output.

I search for -100, and it extracts -99 for me. I place any number, but i stil get -99. What is the problem???

Hashtable table = new Hashtable();

table.Add(-100, "value1");
table.Add(-99, "value2");
table.Add(-98, "value3");
table.Add(-97, "value4");
table.Add(-96, "value5");
table.Add(-95, "value6");
table.Add(-94, "value7");
table.Add(-93, "value8");
table.Add(-92, "value9");
table.Add(-91, "value10");
table.Add(-90, "value11");
table.Add(-89, "value12");
table.Add(-88, "value13");
table.Add(-87, "value14");
table.Add(-86, "value15");


//search by key
int keyToFind = -100;

foreach(DictionaryEntry d in table)
{
if (table.Contains(keyToFind))
{
Console.WriteLine ("{0}\t{1}", d.Key, d.Value);
break;
}
}

Any idea, please? Thanks.
 
R

Richard A. Lowe

That is not the way to lookup a value in a Hashtable. Do it like this:

//search by key
int keyToFind = -100;
Console.WriteLine(table[keyToFind]);

foreach just loops through each key/value pair and the order is NOT
guaranteed no matter what order you add them in.. Contains just indicates
whether a particular value exists, it does nothing to look it up and doesn't
change the current value of the foreach loop.

Richard

Chua Wen Ching said:
Hi i very wonder, why i can't get the right output.

I search for -100, and it extracts -99 for me. I place any number, but i
stil get -99. What is the problem???
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top