c# - 自定义字符顺序

标签 c# enums

我想按自定义顺序对代码列表(两个字符)进行排序。我想到了一个枚举:

    public static enum AlphaCode
    {
        Q, N, A, C
    }

我有一个代码列表,我想按此顺序排序。

List<string> Codes = new List<string>() { "qc", "aq", "nc", "ac" }; 我希望它们按 AlphaCode 的顺序排列。 ,所以它们将像这样输出:

qc nc aq ac

我只列出了一些字母,但AlphaCode将包含按特定顺序排列的所有字母以及一些特殊字符(如点、逗号、分号、方括号)。所以也许枚举不是一个好的选择。

关于如何实现这一目标有什么想法吗?

最佳答案

由于您希望在自定义排序顺序中包含非字母字符,因此使用集合类型而不是 enum 来存储顺序可能更有意义。例如,如果您使用 ListArray,则可以简单地使用索引作为排序的键。

然后,要启用自定义排序,您可以编写一个方法,该方法接受两个字符串并返回一个定义哪个字符串排在前面的 int,并且可以将其传递给该方法的 Sort 方法。 列表。该方法应采用两个字符串,如果第一个字符串“小于”第二个字符串,则返回 -1,如果它们相等则返回 0,或者返回 1 > 如果第一个字符串“大于”第二个字符串。

以下是代码的自定义比较方法的示例:

private static int CodeComparer(string first, string second)
{
    // Short-circuit if one or both strings are null
    if (first == null) return (second == null) ? 0 : -1;
    if (second == null) return 1;

    // The following list should contain all characters in their desired sort order.
    // NOTE: You will need to include UPPERCASE characters as well if expected.
    //    If you want to treat UPPER CASE the same as lower case, then you would call 
    //    ToLower on first and second, and just have lower case characters in this list.
    var sortOrder = new List<char> { 'q', 'n', 'a', 'c', '-', '3', '2', '1' };

    // Since we will loop through both strings one character at a time,
    // we need to get the length of the shorter string (to prevent index out of range)
    int shortestLength = Math.Min(first.Length, second.Length);

    for (int i = 0; i < shortestLength; i++)
    {
        if (first[i] != second[i])
        {
            // When we find two characters that don't match, return the 
            // comparison of their respective indexes in our master list
            return sortOrder.IndexOf(first[i]).CompareTo(sortOrder.IndexOf(second[i]));
        }
    }

    // If all the characters matched, compare the length of the strings. 
    // Normally the shortest comes first, so we do second.CompareTo(first)
    return second.Length.CompareTo(first.Length);
}

现在您可以非常轻松地使用此类:

private static void Main()
{            
    var codes = new List<string>() { "qc", "aq", "nc", "ac", "1a", "3c", "-n" };

    codes.Sort(CodeComparer);

    Console.WriteLine(string.Join(", ", codes));
}

输出:

qc, nc, aq, ac, -n, 3c, 1a

关于c# - 自定义字符顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29245800/

相关文章:

java - 字节神奇地变化

javascript - C# 小于 100 的数字字段总和(静态和动态)

c# - Visual C# 中用户控件的用途是什么?

c# - 使用 ASP.Net 在单击事件期间多次更新标签文本

java - 直接枚举与 Enum<> .. 确切的技术差异是什么?

php - 如何在 PHP 中以整数形式返回枚举列值

ios - 类似枚举的功能的替代品并且能够在 Swift 中扩展

python - 如何键入使用默认值动态创建的枚举?

c# - 如何将带有错误规范(无效用户名或无效密码)的 HttpResponseException 返回给前端?

c# - 使用 NoRM 在 MongoDB 中延迟加载