C# 程序从序列的开头返回指定数量的元素
csharpprogrammingserver side programming更新于 2025/9/13 12:12:00
设置一个数组并使用 OrderByDescending 按降序排列。
int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345};
现在,使用 Take() 方法从开头返回指定数量的元素。
Enumerable<int> unit = 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};
// 排名前两位的产品的销量
IEnumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
foreach (int res in units) {
Console.WriteLine(res);
}
}
}
输出
898 789

