asp.net linq 字符串排序问题

本文探讨了使用LINQ和JavaScript进行字符串数组排序的方法。通过实现自定义比较器,展示了如何在C#中达到与JavaScript相似的排序效果,并解释了序数排序的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一般的弱类型语言中,比如javascript中,我们可以直接按照如下代码排序,正常的排序结果如下

var array=["UnderwearMdseId", "timestamp", "message", "client", "ToolMdseId", "PostureId"];
console.log(array.sort());
//["PostureId", "ToolMdseId", "UnderwearMdseId", "client", "message", "timestamp"] 

如果我们想利用linq的排序来达到类似的效果,那么需要考虑如下的代码


class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, StringComparison.Ordinal);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>() { "UnderwearMdseId", "timestamp", "message", "client", "ToolMdseId", "PostureId" };
            list = list.OrderBy(a => a, new NameComparer()).ToList();
        }
    }

官方解释如下

  • An ordinal sort compares strings based on the numeric value of each Char object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the Stringmethods that compare two strings using ordinal sort rules, see the String operations by category section.

  • 来自http://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值