.NET Framework Bookmark and Share   
 index > .NET Base Class Library > Finding data in a hashtable
 

Finding data in a hashtable

Hello,

I wanted to know if there was any other (or faster) way to access data in a hashtable besides using a foreach?

Thanks,

Tim
tcmo44
Let's say dict is your dictionary and key is the key. You can get data associated with key this way:

C#:
string data = dict[key];

VB:
Dim data As String = dict(key)

EDIT: You can also use TryGetValue if you're not sure whether the key exists in the dictionary or it doesn't.

EDIT2: And I was thinking of a Dictionary, not a HashTable, sorry for that :). HashTable works the same way except you have to cast the output to the correct type:

C#:
string data = (string)dict[key];

VB:
Dim data As String = DirectCast(dict(key), String)
  • Marked As Answer bytcmo44 Tuesday, September 22, 2009 7:13 PM
  •  
Michal Burger
Hi Tim,

check out the System.Collections.Hashtable.ContainsKey() and System.Collections.Hashtable.ContainsValue() method.
If you have got questions about this, just ask.
Mark the thread as answered if the answer helps you. This helps others who have the same problem !
C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/
Heslacher
I've looked at these but it doesn't seem to get me exactly what I want. Let's say I have an hashtable with int's as the keys associated with different strings. If I have one of the keys, what's the best way to find the string associated with the key (while loop using IDictionaryEnumeration, foreach loop, etc.).
tcmo44
Let's say dict is your dictionary and key is the key. You can get data associated with key this way:

C#:
string data = dict[key];

VB:
Dim data As String = dict(key)

EDIT: You can also use TryGetValue if you're not sure whether the key exists in the dictionary or it doesn't.

EDIT2: And I was thinking of a Dictionary, not a HashTable, sorry for that :). HashTable works the same way except you have to cast the output to the correct type:

C#:
string data = (string)dict[key];

VB:
Dim data As String = DirectCast(dict(key), String)
  • Marked As Answer bytcmo44 Tuesday, September 22, 2009 7:13 PM
  •  
Michal Burger
Very helpful. Thanks a lot ...
tcmo44

You can use google to search for other answers

Custom Search

More Threads

• RS232 Serial Port programming in Visual Studio .NET 2003
• SignedXML Class: Canonical XML 1.1 not supported?
• System.Diagnostics.Process as administrator
• Finding the objects loaded in a .net application
• Security: Displaying Windows authentication dialog box
• Handling UNC path names as command line input
• installing .net 1.0a AFTER 1.1 and 2.0 ??
• Problem with 'System.Diagnostics.Process.Start'
• xml comment error
• Accidently deleted .Net Framework 1.1