为什么手动添加到C#字典的项目会添加到字典的开头/结尾



使用字典中的Oxyplot,我希望我的用户可以选择颜色。要用所有Oxycolors填充相应的组合框,我有以下功能:

...
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);
}

正如你所看到的,有一个部分我手动添加了三种颜色,这是色盲同事要求的。问题是,由于某种原因,前两种颜色被添加到列表的顶部,第三种颜色被增加到列表的末尾。使用OrderBy()似乎对字典也没有任何影响。

这种行为的原因是什么?

OrderBy返回IOrderedEnumerable<TSource>,它不会对现有字典进行排序,因此您必须执行类似的操作

AllOxyColors = AllOxyColors.OrderBy(x => x.Key).ToDictionary(pair => pair.Key, pair => pair.Value); 

最新更新