为什么C#OrderBy的字符串顺序小写,大写呢? [英] Why does C# OrderBy with string order lowercase before uppercase?

查看:183
本文介绍了为什么C#OrderBy的字符串顺序小写,大写呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#进行编码,因此我需要订购一系列一个字符串.例如:

I'm coding in C# and I had a situation that needed me to order a series of one character string. example:

var list = new List<string> { "1", "A", "a", "0" };

由于我们都知道 ASCII 表在下"之前列出了上",因此我期望它的排序方式是这样的(0,1,A,a),但是它的排序方式是这样的(0,1,a,A)

Since we all know that the ASCII table lists Upper before Lower, I was expecting this to be ordered like this (0, 1, A, a), but it was ordered like this (0, 1, a, A)

我有一个简单的例子:

        var strs = new List<string> { "1", "A", "a", "0" };
        var orderedStrs = strs.OrderBy(l => l);
        Console.WriteLine("---strs---");
        foreach(var elem in strs){
            Console.WriteLine(elem);
        }
        Console.WriteLine("---orderedStrs---");
        foreach(var elem in orderedStrs){
            Console.WriteLine(elem);
        }

        var chars = new List<char> { '1', 'A', 'a', '0' };
        var orderedChars = chars.OrderBy(ch => ch);
        Console.WriteLine("---chars---");
        foreach(var elem in chars){
            Console.WriteLine(elem);
        }
        Console.WriteLine("---orderedChars---");
        foreach(var elem in orderedChars){
            Console.WriteLine(elem);
        }

这是输出:

        ---strs---
        1
        A
        a
        0
        --- orderedStrs---
        0
        1
        a
        A
        ---chars---
        1
        A
        a
        0
        --- orderedChars---
        0
        1
        A
        a

有人可以回答我这个问题吗?

Can anybody answer me this question?

推荐答案

您可以使用 OrderBy(a => a,StringComparer.Ordinal)

var strs = new List<string> { "1", "A", "a", "0" };
var orderedStrs = strs.OrderBy(l => l);
Console.WriteLine("---strs---");
foreach (var elem in strs.OrderBy(a => a, StringComparer.Ordinal))
{
    Console.WriteLine(elem);
}

结果

---strs---
0
1
A
a

这篇关于为什么C#OrderBy的字符串顺序小写,大写呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆