Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sắp xếp từ theo thứ tự từ điển trong C#

Để sắp xếp mảng chuỗi theo thứ tự alphabet (lexicographical order) trong C#, có thể dùng LINQ orderby hoặc Array.Sort().

Cách 1: Dùng LINQ (khuyên dùng)

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] arr = { "Indian", "Moroccon", "American" };

        var sorted = from a in arr orderby a select a;
        // Hoặc syntax method: var sorted = arr.OrderBy(x => x);

        foreach (string res in sorted)
        {
            Console.WriteLine(res);
        }
    }
}

Cách 2: Dùng Array.Sort (sắp xếp tại chỗ)

Array.Sort(arr); // Sửa đổi mảng gốc
foreach (string s in arr) Console.WriteLine(s);

Kết quả đầu ra

American
Indian
Moroccon

Lưu ý: Sắp xếp mặc định phân biệt chữ hoa/thường (uppercase trước lowercase). Dùng StringComparer.OrdinalIgnoreCase để bỏ qua chữ hoa/thường.