Đặt một mảng và sắp xếp nó theo thứ tự giảm dần bằng OrderByDescending.
int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345}; Bây giờ, hãy sử dụng phương thức Take () để trả về số phần tử được chỉ định ngay từ đầu.
Enumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
Hãy cho chúng tôi 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};
// Volume of top two products
IEnumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
foreach (int res in units) {
Console.WriteLine(res);
}
}
} Đầu ra
898 789