简体   繁体   中英

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 ie if the int in <int, FlowLayoutPanel> represented the FlowLayoutPanels.Height , would the loop above continually give me the tallest panel?

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);
}

You can get First and Last Key from the SortedDictionary which would be minimum and maximum respectively.

int minKey = 0;
int maxKey = 0;
if (panels.Keys.Count >= 2)
{
    minKey = panels.Keys.First();
    maxKey = panels.Keys.Last();
}

You can also use Enumerable.Min and Enumerable.Max like:

minKey = panels.Keys.Min();
maxKey = panels.Keys.Max();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM