LINQ OrderBy 使用真正的 ASCII 排序忽略大小写

LINQ OrderBy igorning case with true ASCII ordering

我正在尝试使用 C# 中的 LINQ 按 ASCII 顺序对字符串(“A”、“_”、“a”)进行排序,同时忽略区分大小写。根据ASCII table,我感兴趣的字符串是:

所以我希望输出是

A, _, a

但是我尝试了所有 StringComparer 变体,其中 none 给出了我想要的输出。以下是我的测试程序和输​​出:

    string[] words = { "A", "_", "a" };
    
    var sortedWords = words.OrderBy(a => a, StringComparer.OrdinalIgnoreCase);
    Console.WriteLine("OrdinalIgnoreCase: " + string.Join(", ", sortedWords));

    sortedWords = words.OrderBy(a => a, StringComparer.CurrentCultureIgnoreCase);
    Console.WriteLine("CurrentCultureIgnoreCase: " + string.Join(", ", sortedWords));

    sortedWords = words.OrderBy(a => a, StringComparer.InvariantCultureIgnoreCase);
    Console.WriteLine("InvariantCultureIgnoreCase: " + string.Join(", ", sortedWords));

输出:

OrdinalIgnoreCase: A, a, _

CurrentCultureIgnoreCase: _, A, a

InvariantCultureIgnoreCase: _, A, a

.net fiddle 这里

如何根据 ASCII 顺序对数组进行排序以获得“A,_,a”?

使用 StringComparer.Ordinal... 使用 StringComparer.OrdinalIgnoreCase 你会忽略大小写,所以它可能会默默地将所有内容转换为大写。

来自 MSDN:

OrdinalIgnoreCase:

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language.

Ordinal:

The StringComparer returned by the Ordinal property performs a simple byte comparison that is independent of language.

示例格式正确:http://ideone.com/0YTUdr