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

เมธอด ElementAt() ใน C#

เมธอด ElementAt(index) ใน LINQ ดึงองค์ประกอบที่ดัชนี (Index) ที่ระบุ (0-based) โยน ArgumentOutOfRangeException หาก Index ไม่ถูกต้อง

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

using System;
using System.Linq;

public class Demo
{
    public static void Main()
    {
        string[] arr = { "One", "Two", "Three", "Four", "Five" };
        string res = arr.ElementAt(0); // Index 0 = "One"
        Console.WriteLine(res);
    }
}

ผลลัพธ์

One

ตัวเลือกปลอดภัย: ElementAtOrDefault(index) คืน Default (null สำหรับ Reference Type) หาก Index Out of Range