Ngôn ngữ LINQ - Toán tử ElementAt
Phương thức ElementAt trong LINQ
Phương thức ElementAt trả về một phần tử theo chỉ mục đã chỉ định trong danh sách.
Nếu chỉ mục được chỉ định nằm ngoài phạm vi của danh sách thì nó sẽ ném ra ngoại lệ "Index out of range". Xin lưu ý rằng chỉ mục là một chỉ số bắt đầu từ 0.
Ví dụ sau đây minh họa phương thức ElementAt trên danh sách kiểu nguyên thủy.
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { "One", "Two", null, "Four", "Five" };
Console.WriteLine("1st Element in intList: {0}", intList.ElementAt(0));
Console.WriteLine("1st Element in strList: {0}", strList.ElementAt(0));
Console.WriteLine("2nd Element in intList: {0}", intList.ElementAt(1));
Console.WriteLine("2nd Element in strList: {0}", strList.ElementAt(1));
Console.WriteLine("intList.ElementAt(9) throws an exception: Index out of range");
Console.WriteLine("---------------------------------------------------");
Console.WriteLine(intList.ElementAt(9));
Đây là kết quả khi biên dịch và thực thi chương trình:
1st Element in intList: 10
1st Element in strList: One
2nd Element in intList: 21
2nd Element in strList: Two
intList.ElementAt(9) throws an exception: Index out of range
-------------------------------------------------------------
Run-time exception: Index was out of range....
Như bạn có thể thấy trong ví dụ trên,intList.ElementAt(9)
ném ra ngoại lệ "Index out of range". Do đó bạn cần phải kiểm tra chỉ mục cẩn thận để tránh xảy ra ngoại lệ khi sử dụng phương thức này.
Bạn có thể sử dụng phương thức ElementAtOrDefault sẽ được trình bày ngay bên dưới để tránh xảy ra ngoại lệ như phương thức ElementAt.