如何按数字升序及自定义颜色顺序对字典转换列表排序?
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
- Primary Sort: First compare the integer keys of your
KeyValuePairitems. If they're different, return the result of that comparison to get ascending order. - Secondary Sort: If the keys are identical, then compare the color values using your custom order. Since the default
CompareTofor yourColorTypemight 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

