Sử dụng phương thức Take () để lấy số phần tử riêng lẻ đầu tiên trong C #.
Đầu tiên, thiết lập một danh sách và thêm các phần tử -
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
myList.Add("Five");
myList.Add("Six"); Bây giờ, sử dụng phương thức Take () để lấy các phần tử từ danh sách. Thêm số phần tử bạn muốn làm đối số -
myList.Take(3)
Đây là mã -
Ví dụ
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);
}
}
} Đầu ra
One Two Three