我正在尝试弄清楚如何创建一个排序字典,其中键以非字母顺序排序。有什么方法可以定义我想要的排序方式吗?
例如,键的顺序可能如下所示:
AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X
虽然前三个字母是按字母顺序排列的,但如果我按原样排序,它们会按错误的顺序排列(由于数字)。另请注意,末尾有 X 或 Y。在代码中,永远只有 X 或 Y。
即使我可以为所有可能组合的排序编写枚举,我也愿意这样做,但我不确定如何使用排序字典和枚举...
我知道这有点含糊,但我们将不胜感激!
干杯!
最佳答案
SortedDictionary<TKey, TValue>
的构造函数之一需要 IComparer<TKey>
,您可以在其中指定字典将用于排序的自定义比较器类。
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
// do your own comparison however you like; return a negative value
// to indicate that x < y, a positive value to indicate that x > y,
// or 0 to indicate that they are equal.
}
}
...
SortedDictionary<string, object> dict =
new SortedDictionary<string, object>(new CustomComparer());
关于c# - 排序字典 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4728168/