This is an offshoot of this question. Consider data thus:
1/1/2000 10000
1/1/2001 10000
1/1/2002 10000
10/1/2003 11000
1/1/2004 11000
1/1/2005 11000
6/1/2006 10000
9/1/2006 12000
This data is being collected into a SortedDictionary
with the dates as the keys. I would like to convert it into this format:
1/1/2000 10000
10/1/2003 11000
6/1/2006 10000
9/1/2006 12000
That is, I want the earliest dated item for any given unique value. Normally when I'm presented with this sort of problem, I would iterate backwards...
for i = items.count - 1 to 1 step -1
if item(i) is like item(i-1) remove item(i)
next
But how do you do that with a SortedDictionary
? Linq provides a reverse enumerator, and an index-ish thing, but Linq is only available on Windows. Is there an easy way to do this within basic VB.net I am unfamiliar with?
I solved this by making a List(Of Date)
, iterating backwards over that, then removing entries from the List
. Then I iterate over the result and remove any key from the SortedDictionary
. But that's seriously ugly and many more lines than I would like.
To remove rows from SortedDictionary by compare item N to N-1 in a dictionary and without use Linq, I propose the following solution :
1-Convert dictionary values into array.
2-Compare item N to N-1 in array.
3-Removing rows by index from dictionary.
'sd is your SortedDictionary
Dim sdArray(sd.Keys.Count - 1) As Integer
sd.Values.CopyTo(sdArray, 0)
For i = sd.Keys.Count - 1 To 1 Step -1
If sdArray(i) = sdArray(i-1) then
Dim index As Integer = 0
For Each p As KeyValuePair(Of DateTime, integer) In sd
if index = i then sd.Remove(p.Key) : Exit For
index += 1
Next
End If
Next
If you want the earliest dated item for any given unique value use this code :
For i = sd.Keys.Count - 1 To 1 Step -1
For j = i - 1 To 0 Step -1
If sdArray(i) = sdArray(j) then
Dim index As Integer = 0
For Each p As KeyValuePair(Of DateTime, integer) In sd
if index = i then sd.Remove(p.Key) : Exit For
index += 1
Next
Exit For
End If
Next
Next