C#字符串长度怎么从小到大排序

c#
983
2024/6/16 20:00:21
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要对C#字符串数组按长度从小到大排序,可以使用LINQ进行排序操作。以下是一个示例代码:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] strings = { "apple", "pear", "banana", "orange" };

        var sortedStrings = strings.OrderBy(s => s.Length);

        foreach (var str in sortedStrings)
        {
            Console.WriteLine(str);
        }
    }
}

运行以上代码将输出:

pear
apple
banana
orange

在这个示例中,我们使用OrderBy方法对字符串数组按长度从小到大排序。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 集合C#能存储啥类型