c# - 排序字典 - C#

标签 c# .net-4.0 enums logic sorteddictionary

我正在尝试弄清楚如何创建一个排序字典,其中键以非字母顺序排序。有什么方法可以定义我想要的排序方式吗?

例如,键的顺序可能如下所示:

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/

相关文章:

c# - 当当前任务阻塞时,如何在 .NET 中安排另一项任务?

c++ - 为嵌套枚举类声明友元插入运算符(运算符<<)

c# - 自动完成搜索列表问题

c# - 自定义依赖解析器会减慢我的 MVC 应用程序吗?

.net - clojure 与 C# 语言

c# - 比较 C#/Unity 中的枚举值?

java - 如何使用内部静态最终字段初始化 Java 枚举?

c# - 一个角度的速度

c# - c#中的toFixed函数

visual-studio-2010 - 为什么 Visual Studio 2010 将 .NET Framework 4.0 Client Profile 作为默认项目类型?