Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Đảo ngược thứ tự phần tử trong List C#

Ví dụ 1: Đảo ngược một đoạn

Sử dụng Reverse(int index, int count):

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 lặp qua các phần tử...");
        List<string>.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext()) {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
        
        list.Reverse(2, 4); // Đảo 4 phần tử từ chỉ số 2
        
        Console.WriteLine("Đảo 4 phần tử từ chỉ số 2:");
        foreach (string res in list) {
            Console.WriteLine(res);
        }
    }
}

Kết quả

Enumerator lặp qua các phần tử...
One
Two
Three
Four
Five
Six
Seven
Eight
Đảo 4 phần tử từ chỉ số 2:
One
Two
Six
Five
Four
Three
Seven
Eight

Ví dụ 2: Đảo ngược toàn bộ List

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 lặp qua các phần tử...");
        List<int>.Enumerator demoEnum = list.GetEnumerator();
        while (demoEnum.MoveNext()) {
            int res = demoEnum.Current;
            Console.WriteLine(res);
        }
        
        list.Reverse(); // Đảo ngược toàn bộ
        
        Console.WriteLine("Các phần tử List...Đã đảo ngược");
        foreach (int i in list) {
            Console.WriteLine(i);
        }
    }
}

Kết quả

Enumerator lặp qua các phần tử...
5
10
20
50
100
Các phần tử List...Đã đảo ngược
100
50
20
10
5