Question SortedDictionary

kaizen

Member
Joined
Mar 12, 2008
Messages
8
Programming Experience
5-10
I am using a SortedDictionary and have a question about sorting the results on the value rather then the key or a way to get top x results and top x bottom results.

The SortedDictionary has a list of stocks as the Key and list of their percent moves over a time period as the value.

Is a SortedDictionary the best way to do it? I do not have to use a SortedDictionary.

VB.NET:
Dim results As New SortedDictionary(Of String, Double)

For Each kvp As KeyValuePair(Of String, Double) In results
    'Get the top x and bottom x reuslts?
    Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value)
Next

Thanks.
 
The whole point of any dictionary is that you use the key as a way to get the value. Using the value to get the key is possible but it's cumbersome and is not optimised in any way, as getting value by key is.

The whole point of a SortedDictionary is to provide a dictionary implementation where the items are sorted by key.

It sounds like using some sort of dictionary is appropriate in your case because you have values that relate to unique keys. If you aren't sorting by key though, using a SortedDictionary is pointless. You may as well just use a regular Dictionary. It sounds to me like a regular Dictionary with a bit of LINQ is the way for you to go:
VB.NET:
Module Module1

    Sub Main()
        Dim stocks As New Dictionary(Of String, Double)

        'Populate stocks here, e.g.
        stocks.Add("WNL", 100.0)

        'Display the top 5 stocks.
        For Each stock In GetTopStocks(stocks, 5)
            Console.WriteLine("{0}: {1}", stock.Key, stock.Value)
        Next

        'Display the bottom 5 stocks.
        For Each stock In GetBottomStocks(stocks, 5)
            Console.WriteLine("{0}: {1}", stock.Key, stock.Value)
        Next

        Console.ReadLine()
    End Sub

    Private Function GetTopStocks(ByVal stocks As Dictionary(Of String, Double), _
                                  ByVal count As Integer) As IEnumerable(Of KeyValuePair(Of String, Double))
        Return (From stock In stocks _
                Order By stock.Value Descending).Take(count)
    End Function

    Private Function GetBottomStocks(ByVal stocks As Dictionary(Of String, Double), _
                                     ByVal count As Integer) As IEnumerable(Of KeyValuePair(Of String, Double))
        Return (From stock In stocks _
                Order By stock.Value Ascending).Take(count)
    End Function

End Module
 
Back
Top