反转整个List或C#中指定范围内的元素顺序
为了反转整个列表中元素的顺序,代码如下-
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<String> list = new List<String>();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
Console.WriteLine("Enumerator iterates through the list elements...");
List<string>.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
list.Reverse(2, 4);
Console.WriteLine("Elements in ArrayList2...Reversed 4 elements beginning from index 2");
foreach (string res in list) {
Console.WriteLine(res);
}
}
}输出结果
这将产生以下输出-
Enumerator iterates through the list elements... One Two Three Four Five Six Seven Eight Elements in ArrayList2...Reversed 4 elements beginning from index 2 One Two Six Five Four Three Seven Eight
示例
让我们看另一个例子-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(5);
list.Add(10);
list.Add(20);
list.Add(50);
list.Add(100);
Console.WriteLine("Enumerator iterates through the list elements...");
List<int>.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext()) {
int res = demoEnum.Current;
Console.WriteLine(res);
}
list.Reverse();
Console.WriteLine("Elements in List...Reversed");
foreach (int i in list) {
Console.WriteLine(i);
}
}
}输出结果
这将产生以下输出-
Enumerator iterates through the list elements... 5 10 20 50 100 Elements in List...Reversed 100 50 20 10 5
热门推荐
1 训练狗狗搜寻
2 如何训练狗狗装死
3 狗狗训练书
6 怎么训练狗狗拜年
8 狗狗训练游戏
10 狗狗嗅觉训练
11 怎么训练狗狗在笼子里不叫
12 怎么训练狗狗站立走路
13 怎么训练狗狗在马桶上
14 狗狗尿尿怎么训练
15 训练狗狗用品
16 泰迪狗狗的训练方法大小便
17 训练狗狗可以打吗
18 王曼丽的狗狗训练