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

โปรแกรม C# ดึงองค์ประกอบสุดท้ายจากอาร์เรย์


ภาพรวม

ดึงองค์ประกอบสุดท้ายของอาร์เรย์ด้วย arr[arr.Length - 1] (index = ความยาว - 1)

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

using System;

public class Demo
{
    public static void Main()
    {
        string[] str = { "Java", "HTML", "jQuery", "JavaScript", "Bootstrap" };
        Console.WriteLine("Array...");
        foreach (string res in str) Console.WriteLine(res);
        Console.WriteLine("Last element: " + str[str.Length - 1]);
    }
}

ผลลัพธ์

Array...
Java
HTML
jQuery
JavaScript
Bootstrap
Last element: Bootstrap

วิธีอื่นๆ

  • LINQ: str.Last() หรือ str.LastOrDefault() (ต้อง using System.Linq;)
  • Array.LastIndexOf - ไม่ใช่สำหรับดึงค่าสุดท้าย แต่หาดัชนีของค่าเฉพาะ
  • Pointer unsafe: fixed(string* p = arr) { var last = p[arr.Length - 1]; } (ไม่แนะนำ)

ข้อควรระวัง

  • อาร์เรย์ว่าง (Length == 0) → arr[-1] โยน IndexOutOfRangeException
  • ควรตรวจสอบ: if (arr.Length > 0) var last = arr[^1]; (C# 8+ index from end operator ^1)