ใช้คำเรียงลำดับตามคำเพื่อเรียงลำดับรายการจากน้อยไปมากหรือมากไปหาน้อย
ต่อไปนี้เป็นรายการ -
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike"); ตอนนี้ให้เราเรียงลำดับรายการจากมากไปน้อย -
myLen = from element in myList orderby element.Length descending select element;
นี่คือรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike");
var myLen = from element in myList
orderby element.Length
select element;
Console.WriteLine("Ascending order...");
foreach (string str in myLen){
Console.WriteLine(str);
}
myLen = from element in myList
orderby element.Length descending
select element;
Console.WriteLine("Descending order...");
foreach (string str in myLen) {
Console.WriteLine(str);
}
}
} ผลลัพธ์
Ascending order... bus truck bicycle motorbike Descending order... motorbike bicycle truck bus