ประกาศอาร์เรย์และเริ่มต้น -
int[] arr = new int[] {
87,
23,
65,
29,
67
}; ในการเรียงลำดับ ใช้เมธอด Sort() และ CompareTo() เพื่อเปรียบเทียบและแสดงผลตามลำดับที่ลดลง -
Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));
ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Text;
public class Demo {
public static void Main(string[] args) {
int[] arr = new int[] {
87,
23,
65,
29,
67
};
// Initial Array
Console.WriteLine("Initial Array...");
foreach(int items in arr) {
Console.WriteLine(items);
}
Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));
// Sorted Array
Console.WriteLine("Sorted Array in decreasing order...");
foreach(int items in arr) {
Console.WriteLine(items);
}
}
} ผลลัพธ์
Initial Array... 87 23 65 29 67 Sorted Array in decreasing order... 87 67 65 29 23