ดึงจำนวนองค์ประกอบที่ระบุจากจุดเริ่มต้นโดยใช้เมธอด 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 };
// คะแนน 5 อันดับแรก
IEnumerable<int> selMarks = marks.AsQueryable()
.OrderByDescending(s => s)
.Take(5);
foreach (int res in selMarks)
{
Console.WriteLine(res);
}
}
}
ผลลัพธ์
95 90 85 72 67