Suppose I have data coming from different sources that tells me information about a large group of stores that has the following (just an example):
Necessary to define what store we're dealing with:
- Store_Name (String)
- Location (String)
Store characteristics:
- Square_Feet (Double)
- No_Employees (Double)
- Years_Open (Double)
- ... (Whatever else)
And the structure of the program I'm working with is such that we will always get the first 2 (defining) characteristics and one or more of the store-specific characteristics. My goal is to conglomerate all the characteristics for each of the specific stores together.
To do this, I have created the following class:
Public Class StoreChars
Public Property Square_Feet as Double = 0
Public Property No_Employees as Double = 0
Public Property Years_Open as Double = 0
...
End Class
And then, in my program, I have created the following:
Dim StoreData As New Dictionary(Of Tuple(Of String, String), StoreChars)
The key being the Store_Name
and Location
as the defining tuple.
So, now, in my code, supposing I just got some data together with the defining characteristics for a set of stores (might be some, might be all... we don't know if we've seen these before or not even), my loop to put in that data looks as follows:
For Each PieceOfInfo in ReturnedData
Dim TupleKey As New Tuple(Of String, String)(PieceOfInfo.Store_Name,
PieceOfInfo.Location)
If Not StoreData.ContainsKey(TupleKey) Then
StoreData.Add(TupleKey, New StoreChars With
{
.Square_Feet = PieceOfInfo.Square_Feet
... (whatever else we got) ...
})
Else
StoreData(TupleKey).Square_Feet = PieceOfInfo.Square_Feet
... (whatever else we got) ...
End If
Next
But this seems to be very slow and I'm wondering if it isn't overly-processor-intensive to create a tuple in each loop, check the existence as a key, etc, but I can't think of a better way to do this.
The other solution I was thinking of was to create a Dictionary(Of String, Dictionary(Of String, StoreChars))
. That would eliminate having to create a Tuple with each loop, but it would mean having to check existence of the keys in 2 separate dictionaries.
If there is a better way to do this, I would LOVE to hear what it is because I find myself having to program solutions like this fairly often!
Also, even though I wrote this code in VB, I'm just as comfortable with a C# solution - I'm just currently working in a VB environment.
StoreData.ContainsKey
you could callStoreData.TryGetValue
. This way you don't have to do a 2nd lookup in yourElse
block. \$\endgroup\$