เพื่อจัดลำดับองค์ประกอบในลำดับแบบจากมากไปน้อย ให้ใช้ ThenBy() และ OrderByDescending
นี่คืออาร์เรย์สตริงของเรา:
string[] myStr = { "Keyboard", "Laptop", "Mouse", "Monitor" };
ตอนนี้ ให้ใช้ OrderByDescending เพื่อจัดลำดับแบบ Descending โดยคำนวณความยาวของแต่ละสตริงและใช้ Lambda Expressions ด้วย
IEnumerable<string> res = myStr.AsQueryable()
.OrderByDescending(ch => ch.Length)
.ThenBy(ch => ch);
ตัวอย่างด้านล่างแสดงโค้ดที่อธิบายไปข้างต้น
ตัวอย่าง
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);
}
}
ผลลัพธ์
Keyboard Monitor Laptop Mouse