1

Using Oxyplot in my dictionary, I want my user to have the option to choose colors. To fill the corresponding combobox with all Oxycolors I have the following function:

    ...
    public Dictionary<string, OxyColor> AllOxyColors { get; set; }
    ...

    /// <summary>
    /// Creates a Dictionary from the fields of the OxyColorsclass
    /// </summary>
    private void InitializeAllOxyColors()
    {
        var colorsValues = typeof(OxyColors)
         .GetFields(BindingFlags.Static | BindingFlags.Public)
         .Where(f => f.FieldType == typeof(OxyColor))
         .Select(f => f.GetValue(null))
         .Cast<OxyColor>()
         .ToList();

        var colorsNames = typeof(OxyColors)
         .GetFields(BindingFlags.Static | BindingFlags.Public)
         .Where(f => f.FieldType == typeof(OxyColor))
         .Select(f => f.Name)
         .Cast<string>()
         .ToList();

        AllOxyColors = colorsNames.Zip(colorsValues, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v);
        AllOxyColors.Remove("Undefined");
        AllOxyColors.Remove("Automatic");
        // Manually added colors for colorblind colleagues
        AllOxyColors.Add("#DE1C1C", OxyColor.Parse("#DE1C1C"));
        AllOxyColors.Add("#13EC16", OxyColor.Parse("#13EC16"));
        AllOxyColors.Add("#038BFF", OxyColor.Parse("#038BFF"));
        // ordering doesn't seem do anything on the dictionary here:
        //AllOxyColors.OrderBy(c => c.Key);
    }

As you can see there is a section where I manually add three colors, that where requested by color blind colleagues. The problem is, that for some reason, the first two colors are added to the top of the list, the third color is added at the end of the list. Using OrderBy() also doesn't seem to have any effect on the dictionary.

What is the reason for this behavior?

Roland Deschain
  • 2,211
  • 19
  • 50
  • Does this answer your question? [The order of elements in Dictionary](https://stackoverflow.com/questions/4007782/the-order-of-elements-in-dictionary) . TLDR: the elements are not stored in any particular order internally. The sequence in which you added them into the dictionary is irrelevant. You can use an OrderedDictionary or SortedDictionary if you need that kind of functionality. – ADyson Nov 15 '19 at 10:07
  • @ADyson it seems like it does, will test with ordered dictionary and report back – Roland Deschain Nov 15 '19 at 10:10
  • Actually from a bit of brief googling it might be that SortedDictionary is closer to what you need. You might need to try both of them out. – ADyson Nov 15 '19 at 10:13

1 Answers1

1

OrderBy returns IOrderedEnumerable<TSource> it won't sort your existing dictionary, so you have to do something like

AllOxyColors = AllOxyColors.OrderBy(x => x.Key).ToDictionary(pair => pair.Key, pair => pair.Value); 
Mihir Dave
  • 3,954
  • 1
  • 12
  • 28