Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order a Dictionary in C#?

Tags:

c#

dictionary

edit: Thanks Jason, the fact that it was a dictionary isn't that important. I just wanted the runtime to have a low runtime. Is that LINQ method fast? Also, I know this is off topic but what does the n => n mean?

I have a list of numbers and I want to make another list with the numbers that appear most at the beginning and the least at the end.

So what I did was when through the list and checked if the number x was in the dictionary. If it wasn't then I made the key x and the value one. If it was then I changed the value to be the value plus one.

Now I want to order the dictionary so that I can make a list with the ones that appear the most at the beginning and the least at the end.

How can I do that in C#? ps. runtime is very important.

like image 899
Daniel Avatar asked Jan 17 '10 13:01

Daniel


1 Answers

So it sounds like you have a Dictionary<int, int> where the key represents some integer that you have in a list and corresponding value represents the count of the number of times that integer appeared. You are saying that you want to order the keys by counts sorted in descending order by frequency. Then you can say

// dict is Dictionary<int, int>
var ordered = dict.Keys.OrderByDescending(k => dict[k]).ToList();

Now, it sounds like you started with a List<int> which are the values that you want to count and order by count. You can do this very quickly in LINQ like so:

// list is IEnumerable<int> (e.g., List<int>)
var ordered = list.GroupBy(n => n)
                  .OrderByDescending(g => g.Count())
                  .Select(g => g.Key)
                  .ToList();

Or in query syntax

var ordered = (from n in list
               group n by n into g
               orderby g.Count() descending
               select g.Key).ToList();

Now, if you need to have the intermediate dictionary you can say

var dict = list.GroupBy(n => n)
               .ToDictionary(g => g.Key, g => g.Count());
var ordered = dict.Keys.OrderByDescending(k => dict[k]).ToList();
like image 55
jason Avatar answered Sep 22 '22 19:09

jason