Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การกลับลำดับสมาชิกใน List ทั้งหมดหรือช่วงที่ระบุใน C#

ภาพรวม

เมธอด List<T>.Reverse() กลับลำดับสมาชิกทั้งหมด และ Reverse(int index, int count) กลับเฉพาะช่วง

ตัวอย่างที่ 1: กลับลำดับ 4 สมาชิกเริ่มจากดัชนี 2

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); // index 2, count 4 -> Three, Four, Five, Six

        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

ตัวอย่างที่ 2: กลับลำดับทั้ง 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 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

สรุป

  • Reverse() กลับทั้ง List (in-place)
  • Reverse(index, count) กลับเฉพาะช่วง ต้องมี index + count <= Count
  • ไม่คืนค่า List ใหม่ แต่อัปเดต List เดิม