Dictionary with ValueTuple as the key
Hi there,
I want to add data to a dictionary with a key that contains 3 fields. I've been advised to use a ValueTuple but have tried all the syntax options that i could find in Google without success.
Ideally it should be like the setup of a databuffer where the key is the databuffercellPk and the value the actual stored number.
My key should contain 3 strings and the value a decimal).
I've tried something like: Dim dctDict as New Dictionary<(String sn, String Tm, String Ac)>, int();
and various other options.
Does anybody had a suggestion how to create the best performing Dictionary Key that exists of 3 strings?
Sub Main 'Initialize collection of data keys Dim dkCollection As New Dictionary(Of dataKey, Integer) For i = 1 To 12 Dim dk As New dataKey() dk.sn = "Actual" dk.tm = $"2020M{i}" dk.ac = "Sales" dkCollection.Add(dk, 10 * i) Next i 'Generate a new key and serach for it Dim searchDk As New dataKey() searchDk.sn = "Actual" searchDk.tm = "2020M2" searchDk.ac = "Sales" 'Search single key Dim resultDk1 As Integer = dkCollection.Item(searchDk) Console.WriteLine($"Single Query Result = {resultDk1}") 'Search multiple keys Dim resultList As List(Of Integer) = dkCollection.Where(Function(x) x.Key.sn = "Actual").Select(Function(y) y.Value).ToList Console.WriteLine($"Single Query Result = {String.Join(",", resultList)}") End Sub ' Define other methods and classes here ' Define other methods and classes here Private Structure dataKey Property sn As String Property tm As String Property ac As String End Structure
The struct can be generated iteratively, in this case in a for loop. When you search for it you can generate a new struct and if all the property are the same it will match what is in the collection. Essentially the struct itself is just a memory pointer, so you can definitely generate them in a loop. Clearly if you try to add a struct with the same three properties, even if the "name" you give to the object is different, it will return an error, since the name of the object itself exist only in the code you see, but not in the compiled version the machine is going to run. Essentially it is just a label to avoid you from knowing the memory location of the object.
Single Query Result = 20
Single Query Result = 10,20,30,40,50,60,70,80,90,100,110,120