You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C#中OrderBy对字符串排序时小写字母排在大写字母之前?

Why does sorting List<string> give a different result than List<char>?

Great question! The difference you're seeing comes down to how .NET handles comparisons for strings vs. individual characters by default:


1. Character sorting uses ordinal (ASCII/Unicode) values

When you sort List<char>, the OrderBy method compares characters directly by their underlying Unicode code points (which match ASCII values for common characters like digits, A-Z, a-z).

As you know from the ASCII table:

  • '0' = 48, '1' = 49
  • 'A' = 65, 'a' = 97

Sorting by these raw values naturally gives 0, 1, A, a—which matches your expected result.

2. String sorting uses culture-sensitive comparison by default

For List<string>, the default OrderBy uses Comparer<string>.Default, which relies on your current system culture's sorting rules instead of raw code points.

Most cultures prioritize case-insensitive sorting logic, and many (like en-US) will sort lowercase letters before uppercase ones when comparing single-character strings. That’s why you’re seeing 0, 1, a, A instead of the ASCII-based order you expected.


Fix: Force ordinal sorting for strings

To make your string sorting match the character sorting behavior, explicitly use StringComparer.Ordinal in the OrderBy method. This tells .NET to compare strings based on their raw Unicode code points (just like it does for chars):

var strs = new List<string> { "1", "A", "a", "0" };
// Use StringComparer.Ordinal to get ASCII/Unicode-based sorting
var orderedStrs = strs.OrderBy(l => l, StringComparer.Ordinal);

// Output will now be: 0, 1, A, a
foreach(var elem in orderedStrs){ Console.WriteLine(elem); }

Bonus: Case-insensitive ordinal sorting (if needed)

If you ever need to sort strings without caring about case but still want to use ordinal rules, you can swap in StringComparer.OrdinalIgnoreCase. But for your specific use case, Ordinal is exactly what you need to get the ASCII-aligned order you expected.


内容的提问来源于stack exchange,提问作者Rui Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:19:07