Dictionary Access: Compound Key and Concatenated String Index

I have a dictionary that I want to get using a key, which is a combination of string ( AcctNum ) and date ( BalDate ).

It seems to me that the easiest way is to create a key by simply converting the date to a string and concatenating:

 MyKey = BalDate.ToString & "|" & AcctNum 

I know that I also have the opportunity to create a composite key by writing a separate class and overriding GetHashCode() and Equals() a la this solution .

For me, a concatenated string is a simpler, albeit less elegant solution. Is there any good reason why I should go using a combined key class approach?

This search is the main theme of the project I'm working on, so my main task (with second second readability).

+4
source share
3 answers

You can also create a custom collection by inheriting from Dictionary(Of TKey, TValue)

 Public Class BalanceDict Inherits Dictionary(Of String, Balance) Public Shadows Sub Add(ByVal bal As Balance) MyBase.Add(bal.BalDate & "|" & bal.AcctNum, bal) End Sub Public Shadows Function TryGetValue(ByVal balDate As Date, ByVal acctNum As String, <OutAttribute()> ByRef bal As Balance) As Boolean Return MyBase.TryGetValue(balDate & "|" & acctNum, bal) End Function End Class 

I do not think that the speed difference between the complex key and the concatenated string is significant. With a composite key, you do not need to convert the date to a string; however, you will have to compute different hash codes and combine them. However, using a specialized dictionary implementation, you can hide the implementation data and decide to change the key generation method at any time without affecting other parts of your program.

+1
source

If performance is most important to you, then using a separate object is likely to be the best solution: you will save the date formatting as a string every time you prepare a key key. In addition, when using a multi-pass key, it is easier to expand if you decide to add additional parts to the key: it is much easier to miss the missing concatenation element than the missing constructor parameter.

+2
source

Use the key for your dictionary.

 MyKey = Tuple.Create(BalDate, AcctNum) 

Tuples are simpler and less error prone than string concatenation. This is better than using a separate class, since you do not need to override GetHashCode () and Equals () yourself.

+1
source

Source: https://habr.com/ru/post/1394005/


All Articles