So basically I'm having an issue with the task I've been given. I won't bore you with the details of the task itself so I'll just give you the relevant info.
I have a dictionary that I need to be sorted by the int[value] that is the highest, well the top five highest to be precise and I need to be able to show the bottom five as well.
Dictionary<string, int> dict = new Dictionary<string, int>();
The strings(keys) hold words that have been read for a text file. The ints (values) hold ints of how many times they were mentioned in the document.
I was going to do it in another way but I was told to do it with a dictionary so please dictionary only help. I would appreciate it if you can explain how it should be done so I can learn as well as complete the task as the aim of the task is to educate myself but I'm finding it a bit hard..
I appreciate all your help in advance, if more info is required please let me know and I'll post it!
In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System. Collection. Generic namespace.
Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function. Just like with other iterables, we can sort dictionaries based on different criteria depending on the key argument of the sorted() function.
Dictionaries do not have any inherent order. But if you want to get the top 5 entries with highest (or lowest) values, you can use a little Linq:
using System.Linq;
...
var top5 = dict.OrderByDescending(pair => pair.Value).Take(5);
var bottom5 = dict.OrderBy(pair => pair.Value).Take(5);
This will return an IEnumerable<KeyValuePair<string, int>>
. To turn it back into a dictionary, again Linq can help. For example:
var top5 = dict.OrderByDescending(pair => pair.Value).Take(5)
.ToDictionary(pair => pair.Key, pair => pair.Value);
Now, top5
is a Dictionary<string, int>
which contains only the 5 elements from dict
with the hightest value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With