Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Dictionary (string, int) by value

Tags:

c#

sorting

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!

like image 352
Zain Avatar asked Jan 28 '14 16:01

Zain


People also ask

Can we sort dictionary in C#?

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.

Can you use sort on a dictionary python?

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.


1 Answers

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.

like image 108
p.s.w.g Avatar answered Oct 21 '22 07:10

p.s.w.g