Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức ElementAt() trong C#

ElementAt(int index) (trong System.Linq) trả về phần tử tại chỉ mục chỉ định (0-based). Ném ArgumentOutOfRangeException nếu index ngoài phạm vi.

Ví dụ

using System.IO;
using System;
using System.Linq;

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

Kết quả

One

Lưu ý: Với IList<T> (như mảng, List), ElementAt sử dụng indexer trực tiếp (O(1)). Với sequence khác, nó duyệt đến vị trí (O(n)).