C# 程式獲取列表中的前三個元素


使用 Take() 方法獲取 C# 中的第一個單獨數字元素。

首先,設定一個列表並新增元素 −

List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
myList.Add("Five");
myList.Add("Six");

現在,使用 Take() 方法從列表中獲取元素。將您想要的元素數新增為引數 −

myList.Take(3)

以下是程式碼 −

示例

 即時演示

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<string> myList = new List<string>();
      myList.Add("One");
      myList.Add("Two");
      myList.Add("Three");
      myList.Add("Four");
      myList.Add("Five");
      myList.Add("Six");
      // first three elements
      var res = myList.Take(3);
      // displaying the first three elements
      foreach (string str in res) {
         Console.WriteLine(str);
      }
   }
}

輸出

One
Two
Three

更新於: 22-6-2020

9K+ 瀏覽量

開始您的 職業生涯

完成課程,獲取認證

開始學習
廣告
© . All rights reserved.