技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營

贊助商

分類目錄

贊助商

最新文章

搜索

C# Sort()和Reverse()對字符串?dāng)?shù)組升序、降序、倒序排序

作者:admin    時(shí)間:2021-5-18 16:15:34    瀏覽:

C#對字符串?dāng)?shù)組排序可以用不同的方法,本文介紹如何使用Sort()Reverse()方法對字符串?dāng)?shù)組進(jìn)行升序、降序排序。

 C# Sort()和Reverse()對字符串?dāng)?shù)組升序、降序、倒序排序
C# Sort()和Reverse()對字符串?dāng)?shù)組升序、降序、倒序排序

使用Sort()對字符串?dāng)?shù)組進(jìn)行升序排序

C# Sort()方法默認(rèn)是對數(shù)組進(jìn)行升序排序,無論數(shù)組是字符串?dāng)?shù)組還是數(shù)值數(shù)組。

示例

using System;

class Program
{
    static void Main()
    {
        string[] pets = new string[]
        {
            "dog",
            "bird",
            "cat"
        };
        // 數(shù)組引用 Array.Sort 方法進(jìn)行排序
        Array.Sort(pets);

        // 遍歷數(shù)組中的字符串并打印它們
        foreach (string pet in pets)
        {
            Console.WriteLine(pet);
        }
    }
}

輸出結(jié)果

bird
cat
dog

使用Reverse()對字符串?dāng)?shù)組進(jìn)行降序排序

要對字符串?dāng)?shù)組進(jìn)行降序排序,需要同時(shí)用到Sort()Reverse()方法。

先要知道,Reverse()是對數(shù)組倒序排序的方法。

我們先用Sort()方法把數(shù)組升序排序,再用Reverse()方法倒序排序,就得到了降序排序了。

示例

using System;

class Program
{
    static void Main()
    {
        string[] pets = new string[]
        {
            "dog",
            "bird",
            "cat"
        };
        // 數(shù)組引用 Array.Sort 方法進(jìn)行升序排序
        Array.Sort(pets);

        // 數(shù)組引用 Array.Reverse 方法進(jìn)行倒序排序
        Array.Reverse(pets);

        // 遍歷數(shù)組中的字符串并打印它們
        foreach (string pet in pets)
        {
            Console.WriteLine(pet);
        }
    }
}

輸出結(jié)果

dog
cat
bird

總結(jié)

本文介紹了C#如何使用Sort()Reverse()對字符串?dāng)?shù)組升序、降序、倒序排序。

知識擴(kuò)展

我們也可以用Ling對字符串?dāng)?shù)組進(jìn)行升序、降序排序,參考文章《C#用Ling對字符串?dāng)?shù)組進(jìn)行升序、降序排序》。

相關(guān)文章

標(biāo)簽: Sort排序  Reverse方法  Sort方法  
x