0

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.

2
  • 6
    Dictionary is not sorted, by design. There is no sense in sorting it. How are you going to use it? Show the practical example and we will try to find the most optimal collection \ solution. Commented Nov 20, 2015 at 5:32
  • You need to copy your dictionary (which is by definition, unsorted) into some other collection (for example, a list), then sort the second collection. Look at the .Net method .toList() Commented Nov 20, 2015 at 5:40

3 Answers 3

3

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);
    }
);
Sign up to request clarification or add additional context in comments.

1 Comment

You can use lambda to make its simpler. BillsList.Sort((firstPair, nextPair) => firstPair.Value.CompareTo(nextPair.Value));
2

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.

Comments

2

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: enter image description here

1 Comment

Excellent choice of example key-value pairs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.