C#程式從序列開頭返回指定數量的元素


設定一個數組,並使用OrderByDescending按降序排列。

int[] prod = { 290, 340, 129, 540, 456, 898, 765, 789, 345};

現在,使用Take()方法從開頭返回指定數量的元素。

Enumerable<int> units = 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};
      // Volume of top two products
      IEnumerable<int> units = prod.AsQueryable().OrderByDescending(s => s).Take(2);
      foreach (int res in units) {
         Console.WriteLine(res);
      }
   }
}

輸出

898
789

更新於:23-6-2020

119次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告