-1

Basically my task is to sort a Dictionary representing cities with their population in DescendingOrder (done), but the problem comes when i have to sort two cities with equal populations by the order of receiving from the console. The function OrderByDescending seems to mess this up and my task gets wrong results.

Here is what the task requires: "If two countries/cities have the same population, keep them in the order in which they were entered."

Here is how i sort the dictionary:

cities = cities.OrderByDescending(x => x.Value).ToDictionary(a => a.Key, b => b.Value);
stuartd
  • 70,509
  • 14
  • 132
  • 163
l337user
  • 7
  • 1
  • 4
    A BCL Dictionary has no concept of order. – TheGeneral Sep 11 '20 at 22:33
  • 1
    A `Dictionary` has no order. If you want a sorted collection, you have to use a collection, that provides an order. For instance a `SortedDictionary` https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2?view=netcore-3.1. – derpirscher Sep 11 '20 at 23:02
  • 1
    @stuartd Even if the original collection was sorted by two attributes via `OrderBy(x => x.ValueA).ThenBy(x => x.ValueB)` the following `ToDictionary(...)` would immediately destroy that order again – derpirscher Sep 11 '20 at 23:05
  • If you want a dictionary that acts like a list, i.e. preserves the order of elements as they are added, you need to use `OrderedDictionary`, not `Dictionary`. See duplicate. Note that it's also important when sorting to use a _stable sort_. Fortunately, the `Enumerable` extension methods like `OrderByDescending()` do in fact use a stable sort. Unfortunately, `OrderedDictionary` is not generic and so is not type-safe. But you can implement a generic alternative without too much trouble. – Peter Duniho Sep 12 '20 at 00:00

1 Answers1

-2

LINQPad example:

void Main()
{
    var cities = new Dictionary<string, int>();
    cities.Add("City A", 10000);
    cities.Add("City B", 20000);
    cities.Add("City C", 20000);
    cities.Add("City D", 30000);

    var query = cities
        .Select((city, index) => new { index, city })
        .OrderByDescending(x => x.city.Value)
        .ThenBy(x => x.index)
        .ToDictionary(a => a.city.Key, b => b.city.Value);

    query.ToArray().Dump();
}
Beau Harder
  • 1,062
  • 1
  • 7
  • 7