简体   繁体   中英

C# sort a dictionary by value

I am sorting a dictionary, consisting of values & keys , by value. I have a hash of words and number of time used, that I want to order by number of time used.

There is a SortedList which is good for a single value , that I want to map it back to the word.

SortedDictionary orders by key, not value.

I could use a custom class, is there a better way.

I did some google searches but I can't find exactly what I am lookign for.

I found the answer

List<KeyValuePair<string, string>> BillsList = aDictionary.ToList();

BillsList.Sort(delegate(KeyValuePair<string, string> firstPair,
    KeyValuePair<string, string> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);

This should do it:

Dictionary<string, string> d = new Dictionary<string, string>
{
  {"A","Z"},
  {"B","Y"},
  {"C","X"}
};

d.OrderBy(x=>x.Value).Select(x=>x.Key);

Will return C, B, A.

Here is using Linq and mapping the Count to the Word:

IDictionary<string, int> wordsAndCount = new Dictionary<string, int>
{
    {"Batman", 987987987},
    {"MeaningOfLife",42},
    {"Fun",69},
    {"Relaxing",420},
    {"This", 2}
};

var result = wordsAndCount.OrderBy(d => d.Value).Select(d => new 
{
   Word = d.Key,
   Count = d.Value
});

Result: 在此处输入图片说明

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