หากต้องการแสดงสามองค์ประกอบสุดท้ายจากรายการ ให้ใช้เมธอด Take() หากต้องการย้อนกลับ ให้ใช้เมธอด Reverse()
ประการแรก ประกาศรายการและเพิ่มองค์ประกอบลงไป -
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four"); ตอนนี้ ใช้วิธี Take() กับ Reverse() เพื่อแสดงองค์ประกอบสามรายการสุดท้ายจากรายการในลำดับที่กลับกัน -
myList.Reverse<string>().Take(3);
ต่อไปนี้เป็นรหัส −
ตัวอย่าง
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
List<string> myList = new List<string>();
myList.Add("One");
myList.Add("Two");
myList.Add("Three");
myList.Add("Four");
// first three elements
var res = myList.Reverse<string>().Take(3);
// displaying last three elements
foreach (string str in res) {
Console.WriteLine(str);
}
}
} ผลลัพธ์
Four Three Two