ตั้งค่าอาร์เรย์และจัดเรียงจากมากไปหาน้อยโดยใช้ OrderByDescending
int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345}; ตอนนี้ ใช้เมธอด Take() เพื่อส่งคืนองค์ประกอบตามจำนวนที่ระบุตั้งแต่ต้น
Enumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
ให้เราดูรหัสที่สมบูรณ์
ตัวอย่าง
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345};
// Volume of top two products
IEnumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
foreach (int res in units) {
Console.WriteLine(res);
}
}
} ผลลัพธ์
898 789