C# 程式以逆序顯示列表中的後三個元素
要顯示列表中的後三個元素,請使用 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
廣告