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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP