Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để sử dụng các phương thức Remove, RemoveAt, RemoveRange trong bộ sưu tập danh sách C #?

Để triển khai các phương thức Remove () và RemoveAt () trong C #, hãy thử đoạn mã sau -

Đầu tiên, hãy thiết lập một danh sách.

List<string> myList = new List<string>() {
   "mammals",
   "reptiles",
   "amphibians",
   "vertebrate"
};

Bây giờ, hãy sử dụng phương thức Remove () để xóa một phần tử.

myList.Remove("reptiles");

Bây giờ, hãy sử dụng phương thức RemoveAt () để xóa một phần tử bằng cách đặt vị trí.

myList.RemoveAt(2);

Sau đây là mã hoàn chỉnh -

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> myList = new List<string>() {
         "mammals",
         "reptiles",
         "amphibians",
         "vertebrate"
      };

      Console.Write("Initial list...");
      foreach (string list in myList) {
         Console.WriteLine(list);
      }

      Console.Write("Using Remove() method...");
      myList.Remove("reptiles");

      foreach (string list in myList) {
         Console.WriteLine(list);
      }

      Console.Write("Using RemoveAt() method...");
      myList.RemoveAt(2);

      foreach (string list in myList) {
         Console.WriteLine(list);
      }
   }
}

Đây là một ví dụ triển khai phương thức RemoveRange ().

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<int> myList = new List<int>();
      myList.Add(5);
      myList.Add(10);
      myList.Add(15);
      myList.Add(20);
      myList.Add(25);
      myList.Add(30);
      myList.Add(35);

      Console.Write("Initial list...");
      foreach (int list in myList) {
         Console.WriteLine(list);
      }

      Console.Write("New list...");
      int rem = Math.Max(0, myList.Count - 3);
      myList.RemoveRange(0, rem);

      foreach (int list in myList) {
         Console.Write("\n"+list);
      }
   }
}