Forum Discussion
MarcR
4 years agoContributor II
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 succ...
- 4 years ago
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 StructureThe 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
MarcR
4 years agoContributor II
Hi Christian,
That would also be an issue to get the data in and out of this dictionary. My alternative would be to delimit the items with a pipe and then combine the search fields to this unique key. The only disadvantage is that i cannot search for a specific key (or filter on that). Ideally i would work with it as we do with a datacellPK but i don't see any better solution right now.
ChristianW
OneStream Employee
4 years agoDid you try this:
dctDict3.add(New tuple(Of String, String)("Christian", "Marc"), 100)
brapi.ErrorLog.LogMessage(si, dctDict3(New tuple(Of String, String)("Christian", "Marc")))
Related Content
- 2 years ago
- 1 year ago
- 2 years ago