user1713153
user1713153

Reputation: 219

sort Dictionary by generic value

I have tried to sort a Dictionary object by value which is generic.

Here is my code

Dictionary<string, ReportModel> sortedDic = new Dictionary<string, ReportModel>();
Dictionary<string, ReportModel> rDic = new Dictionary<string, ReportModel>();
var ordered = sortedDic.OrderByDescending(x => x.Value.totalPurchase);
foreach (var item in ordered)
{                           
    rDic.Add(item.Key, item.Value);
}

The variable, ordered, just has the same order like sortedDic. What is wrong with this? Any idea?

Upvotes: 1

Views: 94

Answers (2)

WhyMe
WhyMe

Reputation: 535

When adding the items back to the dictionary, it would not keep their order. You can either:

  1. Use the following implementation.
  2. Use a list in the below form.

    IEnumrable> lst=
       sortedDic.OrderByDescending(x => x.Value.totalPurchase).ToArray();
  3. [EDIT] If you don't mind the key changing then you can use SortedDictionary<,>.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

This happens because Dictionary is generally an unordered container*. When you put the data into rDic, it becomes unordered again.

To retain the desired order, you need to put the results into a container that explicitly keeps the ordering that you supply. For example, you could use a list of KeyValuePair<string,ReportModel>, like this:

IList<KeyValuePair<string,ReportModel>> ordered = sortedDic
    .OrderByDescending(x => x.Value.totalPurchase)
    .ToList();


* Due to the way the Dictionary<K,V> is implemented by Microsoft, it happens to retain the insertion order, but that is incidental and undocumented, so it may change in the future versions, and should not be relied upon.

Upvotes: 4

Related Questions