You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按数字升序及自定义颜色顺序对字典转换列表排序?

Solution for Your Custom Sorting Rules

Great question! To implement your two-step sorting rule (first by the integer key ascending, then by the custom color order Red < Yellow < White), you'll need to adjust your Sort delegate to handle both conditions in the right priority. Here's how to do it cleanly:

Step-by-Step Explanation

  1. Primary Sort: First compare the integer keys of your KeyValuePair items. If they're different, return the result of that comparison to get ascending order.
  2. Secondary Sort: If the keys are identical, then compare the color values using your custom order. Since the default CompareTo for your ColorType might not follow Red < Yellow < White, we'll use a priority mapping to enforce this order.

Code Implementation

First, define a priority dictionary to map each color to a numerical value that matches your desired order. Then use this in the sorting lambda:

// Define the color priority mapping (Red = highest priority, White = lowest)
var colorPriority = new Dictionary<ColorType, int>
{
    { ColorType.Red, 0 },
    { ColorType.Yellow, 1 },
    { ColorType.White, 2 }
};

// Convert your map to a list
List<KeyValuePair<int, ColorType>> myList = map.ToList();

// Apply the two-step sort
myList.Sort((pair1, pair2) =>
{
    // First compare the integer keys ascending
    int keyComparison = pair1.Key.CompareTo(pair2.Key);
    if (keyComparison != 0)
    {
        return keyComparison;
    }
    
    // If keys are equal, compare using the custom color order
    return colorPriority[pair1.Value].CompareTo(colorPriority[pair2.Value]);
});

Alternative: If Your ColorType Enum is Already in Order

If your ColorType enum is defined in the exact order Red, Yellow, White (like below), you can skip the priority dictionary and just compare the enum values directly for the secondary sort:

public enum ColorType
{
    Red,
    Yellow,
    White
}

In that case, the sorting lambda simplifies to:

myList.Sort((pair1, pair2) =>
{
    int keyComparison = pair1.Key.CompareTo(pair2.Key);
    return keyComparison != 0 ? keyComparison : pair1.Value.CompareTo(pair2.Value);
});

This works because enum CompareTo uses the underlying integer values of the enum members, which are assigned sequentially starting at 0 by default.

Why This Works

  • The primary sort ensures all items are grouped by their integer key in ascending order.
  • The secondary sort only kicks in when two items have the same key, ensuring they follow your custom color hierarchy.

内容的提问来源于stack exchange,提问作者Justeasy StackAttacka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:17:41