Get "closest" Key in Visual Basic Dictionary
In Visual Basic I have a Dictionary which holds a Date as a key and a custom class as value (I will use a String in the example). I keep track of a list where a date is saved with a value. For example, lets say I have a dictionary with the following values:
Dim dict As Dictionary(Of Date, String)
dict.Add(DateTime.Now, "test one") // Suppose the time of this date is 12:03:10
dict.Add(DateTime.Now, "test two") // Suppose the time of this date is 13:07:20
dict.Add(DateTime.Now, "test three") // Suppose the time of this date is 14:15:30
dict.Add(DateTime.Now, "test four") // Suppose the time of this date is 15:19:40
Now the system gives me a date which does not have a value, but needs one similar to the first previous date. Let's say I get the date with time 14:00:00, I will need the value of "test two开发者_Go百科" because 13:07:20 is the first key lower than 14:00:00 (a key which is not actually available in the dictionary keys).
Assuming that the list could be very big, is there a way/what would be the best way to find the key I am looking for?
(Couldnt post on my own question within 8 hours...)
Using my dictionary and using the dict.Keys I did:
Dim lookupDate As Date = Date.Parse("01/01/2008 12:17:39")
Dim query = dict.Keys.AsQueryable().Where(Function(singleKey) singleKey < lookupDate)
Dim result As String = query.Last().ToString()
This solution should have better performance because of the iQueryable if im correct.
The Keys
method will give you an array containing all the keys.
Dim k As Variant
k = dict.Keys
You can then loop through that array to find the key that satisfies the criterion. Here's an example, not thoroughly checked...
Dim myDate As Variant
Dim myKey As Variant
myDate = 1234 ' or whatever your target date is
Dim i As Long
myKey = k(0)
For i = 1 To UBound(k)
If k(i) < myDate And k(i) > myKey Then
myKey = k(i)
End If
Next i
myKey
should now contain the key that satisfies your criterion.
精彩评论