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

โปรแกรม C# คืนค่าจำนวนองค์ประกอบที่ระบุจากท้ายอาร์เรย์

ใช้เมธอด TakeLast() เพื่อคืนค่าองค์ประกอบจากท้ายอาร์เรย์

มาประกาศและเริ่มต้นอาร์เรย์ก่อน:

int[] prod = { 110, 290, 340, 540, 456, 698, 765, 789 };

ตอนนี้ ให้ดึง 3 องค์ประกอบสุดท้าย:

IEnumerable<int> units = prod.AsQueryable().TakeLast(3);

มาดูโค้ดทั้งหมดกัน

ตัวอย่าง

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

public class Demo
{
    public static void Main()
    {
        int[] prod = { 110, 290, 340, 540, 456, 698, 765, 789 };
        // ค่าของผลิตภัณฑ์ 3 อันดับสุดท้าย
        IEnumerable<int> units = prod.AsQueryable().TakeLast(3);
        
        foreach (int res in units)
        {
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

698
765
789