Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ดึงสามองค์ประกอบแรกจากลิสต์

ใช้เมธอด Take(n) ของ LINQ ดึง n องค์ประกอบแรกจากลำดับ

ตัวอย่างโค้ด

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        List myList = new List { "One", "Two", "Three", "Four", "Five", "Six" };
        
        var res = myList.Take(3); // 3 ตัวแรก
        
        foreach (string str in res) Console.WriteLine(str);
    }
}

ผลลัพธ์

One
Two
Three

คู่กับ Skip: Skip(n) ข้าม n ตัวแรก ใช้ร่วมกันทำ Pagination ได้ (Skip(pageSize * page).Take(pageSize))