Search code examples
c#linqdictionary

How to get the maximum/minimum value from a SortedDictionary?


I have built a SortedDictionary<int, FlowLayoutPanel> panels as prescribed. I currently am looping over the dictionary like so

foreach (var key in panels.Keys.ToList())
{
    FlowLayoutPanel tallestPanel = panels[key];
}

to get the entry with the maximum key value. I am trying to now write another loop that continually applies an operation until the Count of the dictionary is 0. Within this loop I need to get the maximum and minimum value from the dictionary on each iteration. I have read over the SortedDictionary MSDN entry and it looks like I need to use linq to accomplish this. Is this true? How would I do that? (I've never touched linq)

And a bonus question that I can't find a good answer to, do SortedDictionaries sort from largest to smallest value i.e. if the int in <int, FlowLayoutPanel> represented the FlowLayoutPanels.Height, would the loop above continually give me the tallest panel?


Solution

  • Since the keys are sorted in panels.Keys, the minimum and maximum keys will simply be the first and last items in panels.Keys. You don't need LINQ to do this:

    var keys = panels.Keys.ToList();
    // manually-determined indexes
    var min = panels[keys[0]];
    var max = panels[keys[keys.Count - 1]];
    

    Although arguably, it's clearer if you use it:

    var keys = panels.Keys.ToList();
    // or with LINQ
    var min = panels[keys.First()];
    var max = panels[keys.Last()];
    

    If you want to get these values from inside a loop that's looping through panel.Keys.ToList() and removing each item from the dictionary as it goes (which is what I think you're describing), the minimum is always the current, and the maximum is always the last.

    var keys = panels.Keys.ToList();
    var max = panels[keys.Last()];
    foreach (var key in keys)
    {
        var min = panels[key];
        // do stuff
        panels.Remove(min);
    }