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

เมธอด Linq ElementAt ใน C#


ภาพรวม

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

รูปแบบการใช้งาน

string[] names = { "Jack", "Pat", "David" };
string name = names.AsQueryable().ElementAt(1); // "Pat"

ตัวอย่างโค้ดเต็ม: สุ่มชื่อ

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] str = { "Jack", "Pat", "David" };
        Random r = new Random();
        string res = str.AsQueryable().ElementAt(r.Next(0, str.Length));
        Console.WriteLine("Random Name = '{0}'", res);
    }
}

ผลลัพธ์ตัวอย่าง

Random Name = 'Jack'

ข้อสังเกต

  • สำหรับ List<T> หรืออาร์เรย์ ควรใช้ list[index] โดยตรง เร็วกว่า
  • ElementAt เหมาะสำหรับ IEnumerable<T> ที่ไม่รองรับการเข้าถึงแบบสุ่ม (random access)
  • มี ElementAtOrDefault() คืนค่า default หากดัชนีอยู่นอกช่วง