Hashtable in .Net
Hashtables are my preferred way to keep informations in memory. I think that they’re powerful and really simple to use.
The Hashtable class resides into the System.Collections namespace and uses an Object as Key and an Object as Value for the items so it’s really versatile and doesn’t give you any constraint about types, you can store all that u want in them.
Imports System.Collections 'Create a simple class Public Class Person private _Name; private _Surname; Public Sub New() _Name = "" _Surname = "" End Sub Public Property Name() As String Get Return _Name End Get Set(ByVal Value As String) _Name=Value End Set End Property Public Property Surname() As String Get Return _Surname End Get Set(ByVal Value As String) _Surname=Value End Set End Property End Class 'Let's assume we have a chief for each sector of an enterprise 'and we want to keep in memory their names public chiefs as new Hashtable public sub CreateChiefsTable() dim p1 as new Person p1.Name="John" p1.Surname="Smith" 'add the person into the hashtable and identify him 'with the sector name as key. chiefs.Add("Sector Alpha",p1) dim p2 as new Person p2.Name="Michael" p2.Surname="Brown" 'add a second person. chiefs.Add("Sector Beta",p2) end sub 'Accessing the data is really simple. 'Create a sub that shows the name and surname of the chief 'of a specific sector. public sub ShowChiefInfo(ByVal Sector as string) if chiefs.ContainsKey(Sector) then dim p as person p=directCast(chiefs(Sector),Person) MessageBox.show(p.Name + " " + p.Surname) else MessageBox.Show("Wrong sector") end if end sub 'Cycling the items is easy too 'Create a sub that shows each sector chief info public sub ShowChiefs() 'cycle all Hastables keys for each Sector as string in chiefs.keys dim p as person p=directCast(chiefs(Sector),Person) MessageBox.show(Sector + ": " + p.Name + " " + p.Surname) next end sub
Download this code: Hashtable.vb.txt
That’s all.
TAGS: Asp.net, dotnet, code snippet, seo, search engine optimization, visual studio.net, sample code, c#, vb.net























