0

I have two collections:

One the one hand, a dictionary containing Products with Id's and on the other hand, a list of Id's containing the order in which they should be ordered.

The dictionary contains objects like this:

enter image description here

The sorting list is just a simply int array

{1, 3, 2, 5, 7...}

To sort the dictionary using the orderArray, I'm using the following code:

foreach (var index in orderList)
{
     dictionary.Value.Sort((first, second) =>
    {
       var x = first["ID"].Equals(index).CompareTo(second["ID"].Equals(index));
       return x;
    });
}

This code works fine for dictionaries up to and including 16 items, but as soon as a larger dictionary is passed in, the sorting algorithm breaks. What could be the cause of this?

  • 5
    You can't sort a dictionary – Sean Jul 02 '20 at 13:44
  • `dictionary.Values` doesn't have a `Sort` method (as that wouldn't make sense: a dictionary is an unsorted collection, and `Values` is just a way of iterating over the values in the dictionary, in some undefined order). What method are you calling there? – canton7 Jul 02 '20 at 13:52
  • 2
    Possibly use a [SortedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2?view=netcore-3.1)? – Idle_Mind Jul 02 '20 at 14:00
  • Does this answer your question? [How do you sort a dictionary by value?](https://stackoverflow.com/questions/289/how-do-you-sort-a-dictionary-by-value) – Jawad Jul 02 '20 at 14:20
  • 1
    the question, why 16 items work?can you share the 17 item? if you have 18 items it's work? – Mohammed Sajid Jul 02 '20 at 14:36
  • Sajid - That's indeed the question. Collections <= 16 items work fine but larger collections break. I have no idea what could be the cause of this. – Michiel Wouters Jul 03 '20 at 07:38
  • 1
    The initial size of a dictionary is 16 elements. After that, it will re-allocate some larger backing storage and move everything over into it. Presumably that's messing with whatever you're doing, but it's not clear *what* you're doing, because your code won't compile, because `dictionary.Values.Sort` isn't a method. – canton7 Jul 03 '20 at 08:37

0 Answers0