Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Comparing Two HashTables
Published: 12/4/2007
XMl / RSS

I wrote a little function over at VBCity.com for my man Conor that illustrates one possible way to enumerate two HashTables, comparing their keys and values to see if they are identical. I thought I'd post it up here because ennumerating dictionary objects is never straight forward. You can modify the routine to just check keys, or just values, or check keys and values in no particular order pretty easily, so enjoy...

VB:
Public Function CompareHashtables(ByVal HashTable1 As Hashtable, ByVal HashTable2 As Hashtable) As Boolean

    If (HashTable1.Count <> HashTable2.Count) Then
        Return False
    Else
        Dim clsEnumerator1 As IEnumerator = HashTable1.Keys.GetEnumerator()
        Dim clsEnumerator2 As IEnumerator = HashTable2.Keys.GetEnumerator()
        clsEnumerator1.Reset()
        clsEnumerator2.Reset()
        For i As Integer = 1 To HashTable1.Count
            ' get next item...
            clsEnumerator1.MoveNext()
            clsEnumerator2.MoveNext()
            ' get current item...
            Dim sKey1 As Object = clsEnumerator1.Current
            Dim sKey2 As Object = clsEnumerator2.Current
            ' check key...
            If (Not sKey1 Is sKey2) Then Return False
            ' check value...
            If (Not HashTable1(sKey1) Is HashTable2(sKey2)) Then Return False
        Next
    End If

    Return True

End Function	
	
C#:
public bool CompareHashtables(Hashtable HashTable1, Hashtable HashTable2)
{

	if (HashTable1.Count != HashTable2.Count)
		return false;
	else
	{
		IEnumerator clsEnumerator1 = HashTable1.Keys.GetEnumerator();
		IEnumerator clsEnumerator2 = HashTable2.Keys.GetEnumerator();
		clsEnumerator1.Reset();
		clsEnumerator2.Reset();
		for (int i = 1; i <= HashTable1.Count; i++)
		{
			// get next item...
			clsEnumerator1.MoveNext();
			clsEnumerator2.MoveNext();
			// get current item...
			object sKey1 = clsEnumerator1.Current;
			object sKey2 = clsEnumerator2.Current;
			// check key...
			if (sKey1 != sKey2) return false;
			// check value...
			if (HashTable1[sKey1] != HashTable2[sKey2]) return false;
		}
	}

	return true;

}	
	

Of course, if you wanted to enumerate just one HashTable, you would probably do something like this instead:

VB:
For Each clsPair As DictionaryEntry In HashTable1
    Debug.WriteLine(clsPair.Key.ToString() & " = " & clsPair.Value.ToString())
Next	
	
C#:
foreach (DictionaryEntry clsPair in HashTable1)
{
	System.Diagnostics.Debug.WriteLine(clsPair.Key.ToString() + " = " + clsPair.Value.ToString());
}	
	



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.