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

Sắp xếp mảng giảm dần với OrderByDescending và ThenBy trong C#

Để sắp xếp các phần tử theo thứ tự giảm dần và áp dụng sắp xếp thứ cấp, ta kết hợp OrderByDescending() với ThenBy().

Ví dụ minh họa

Mảng chuỗi ban đầu:

string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };

Sắp xếp giảm dần theo độ dài chuỗi, sau đó sắp xếp tăng dần theo tên cho các chuỗi cùng độ dài:

IEnumerable<string> res = myStr.AsQueryable()
    .OrderByDescending(ch => ch.Length)
    .ThenBy(ch => ch);

Mã nguồn hoàn chỉnh

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };
        IEnumerable<string> res = myStr.AsQueryable()
            .OrderByDescending(ch => ch.Length)
            .ThenBy(ch => ch);

        foreach (string arr in res)
            Console.WriteLine(arr);
    }
}

Kết quả đầu ra

Keyboard
Monitor
Laptop
Mouse

Giải thích: "Keyboard" (8 ký tự) và "Monitor" (7 ký tự) đứng trước. Hai từ cùng 6 ký tự ("Laptop", "Mouse") được sắp xếp theo bảng chữ cái.