排序字典 - C#
我试图弄清楚如何创建一个排序字典,其中键以非字母顺序排序。有没有办法可以定义我想要的排序方式?
例如,键的顺序可能如下:
AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X
虽然前三个字母是按字母顺序排列的,但如果我按原样排序,它们将以错误的顺序排列(由于数字)。另请注意,末尾有 X 或 Y。在代码中,只会有一个 X 或一个 Y。
即使我可以编写一个枚举来排序所有可能的组合,我也愿意这样做,但我不确定如何使用排序的字典和枚举...
我知道这有点模糊,但任何帮助将不胜感激!
干杯!
I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner. Is there a way I can define the way I want it to sort?
For example, the keys might be in order like the following:
AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X
Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end. In the code, there will only ever be an X or a Y.
Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...
I know this is a bit vague, but any help would be much appreciated!
Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SortedDictionary
的构造函数之一采用IComparer
,您可以在其中指定字典将用于排序的自定义比较器类。One of the constructors for
SortedDictionary<TKey, TValue>
takes anIComparer<TKey>
, where you can specify a custom comparer class that the dictionary will use for sorting.您可以:
创建一个类来封装这些键并重写 == 运算符、
Object.Equals
方法和Object.GetHashCode
方法。还让该类实现 IComparable 接口,以便平等规则自动以正确的方式对您的键进行排序。现在,您只需将这些键放入 SortedDictionary 或 SortedList,它会自动按照您想要的方式排序。或
实现一个 IComparer 对象来比较这些对象按照您想要的方式字符串,并在构造 SortedDictionary 时指定 IComparer 或排序列表。
You can :
Create a class that encapsulates those keys and override the == operator,
Object.Equals
method and theObject.GetHashCode
method. Also have the class implement the IComparable interface such that the rules for equality will automatically sort your keys the right way. Now you can simply place those keys in a SortedDictionary or SortedList and it will automatically sort the way you want.OR
Implement an IComparer object that compares those strings the way you want, and specify the IComparer when constructing a SortedDictionaryor SortedList.