简体   繁体   中英

How can I order a Dictionary in C#?

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.

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

The following information is provided as presented at: http://www.dotnetperls.com/sort-dictionary

Dictionary has no Sort method. If we need to loop through the Dictionary contents in sorted order, we must separately acquire the elements and sort them. This is done with the Keys and Values properties and a List instance.

Sort keys

This example solves the problem by using the Keys property on the Dictionary instance, and then the ToList extension method and the Sort instance method.

First, an example Dictionary is created and populated with the Add method; next, the ToList and Sort methods are used on the Keys; finally, the resulting List is looped through using the foreach-loop construct. Also, please notice how the var implicit typed keyword is used throughout, to reduce syntactic redundancy.

Program that sorts keys in Dictionary [C#]

 using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Create dictionary and add five keys and values. var dictionary = new Dictionary<string, int>(); dictionary.Add("car", 2); dictionary.Add("apple", 1); dictionary.Add("zebra", 0); dictionary.Add("mouse", 5); dictionary.Add("year", 3); // Acquire keys and sort them. var list = dictionary.Keys.ToList(); list.Sort(); // Loop through keys. foreach (var key in list) { Console.WriteLine("{0}: {1}", key, dictionary[key]); } } } 

Output

 apple: 1 car: 2 mouse: 5 year: 3 zebra: 0 

Sort values

Next we show how to sort the values in a Dictionary. We see a console program you can compile in Visual Studio and run. It adds keys to a Dictionary and then sorts them by their values. Remember that Dictionary instances are not initially sorted in any way. We use the LINQ orderby keyword in a query statement.

OrderBy Clause Program that sorts Dictionary [C#]

 using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example dictionary. var dictionary = new Dictionary<string, int>(5); dictionary.Add("cat", 1); dictionary.Add("dog", 0); dictionary.Add("mouse", 5); dictionary.Add("eel", 3); dictionary.Add("programmer", 2); // Order by values. // ... Use LINQ to specify sorting by value. var items = from pair in dictionary orderby pair.Value ascending select pair; // Display results. foreach (KeyValuePair<string, int> pair in items) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); } // Reverse sort. // ... Can be looped over in the same way as above. items = from pair in dictionary orderby pair.Value descending select pair; } } 

Output

 dog: 0 cat: 1 programmer: 2 eel: 3 mouse: 5 

Descending Keyword

Descending sort

 var items = from pair in dictionary orderby pair.Value descending select pair; 

Example output

 mouse: 5 eel: 3 programmer: 2 cat: 1 dog: 0 

Use the GroupBy extension on IEnumerable() to group the numbers and extract the count of each. This creates the dictionary from the list and orders it in one statement.

var ordered = list.GroupBy( l => l )
                  .OrderByDescending( g => g.Count() )
                  .ToDictionary( g => g.Key, g.Count() );
    List<KeyValuePair<type, type>> listEquivalent = 
new List<KeyValuePair<type, type>>(dictionary);    

    listEquivalent.Sort((first,second) =>
            {
                return first.Value.CompareTo(second.Value);
            });

Something like that maybe?

edit: Thanks Jason for the notice on my omission

You may also consider using SortedDictionary.

It sorts the items on the basis of key, while insertion. more..

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