ใช้เมธอด 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