รับองค์ประกอบตามจำนวนที่ระบุตั้งแต่ต้นโดยใช้เมธอด Take()
ต่อไปนี้เป็นอาร์เรย์ของเรา
int[] marks = { 35, 72, 50, 90, 95, 85, 52, 67 }; ตอนนี้ ใช้ OrderByDescending เพื่อเรียงลำดับองค์ประกอบจากมากไปหาน้อย จากนั้นใช้วิธี Take() เพื่อรับองค์ประกอบ
marks.AsQueryable().OrderByDescending(s => s).Take(5);
เรามาดูตัวอย่างฉบับสมบูรณ์กัน
ตัวอย่าง
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
int[] marks = { 35, 72, 50, 90, 95, 85, 52, 67 };
// top 5 student marks
IEnumerable<int> selMarks = marks.AsQueryable().OrderByDescending(s => s).Take(5);
foreach (int res in selMarks) {
Console.WriteLine(res);
}
}
} ผลลัพธ์
95 90 85 72 67