使用GetRange()
方法获取元素范围-
首先,设置一个列表并添加元素-
List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50);
现在,在新列表下获得索引1和3之间的元素范围-
List<int> myList = arr1.GetRange(1, 3);
这是完整的代码-
using System; using System.Collections.Generic; public class Demo { public static void Main() { List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); Console.WriteLine("Initial List ..."); foreach (int i in arr1) { Console.WriteLine(i); } Console.WriteLine("Getting elements between a range..."); List<int> myList = arr1.GetRange(1, 3); foreach (int res in myList) { Console.WriteLine(res); } } }
输出结果
Initial List ... 10 20 30 40 50 Getting elements between a range... 20 30 40