Thiết lập mảng và sắp xếp giảm dần dùng OrderByDescending.
int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345 };
Bây giờ, dùng phương thức Take() để trả về số phần tử chỉ định từ đầu.
Enumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
Hãy xem mã hoàn chỉnh.
Ví dụ
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 };
// Thể tích 2 sản phẩm hàng đầu
IEnumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
foreach (int res in units) {
Console.WriteLine(res);
}
}
}
Kết quả
898 789