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

Làm thế nào để sử dụng RemoveAt trong C # ArrayList?

Phương thức RemoveAt trong C # được sử dụng để xóa một phần tử trong danh sách ở vị trí bạn đã đặt.

Đầu tiên, đặt các phần tử trong danh sách -

var subjects = new List<string>();
subjects.Add("Physics");
subjects.Add("Chemistry");
subjects.Add("Biology");
subjects.Add("Science");

Để loại bỏ một phần tử, hãy đặt chỉ mục từ nơi bạn muốn loại bỏ phần tử đó. Sau đây là xóa phần tử khỏi vị trí thứ 3 -

subjects.RemoveAt(2);

Hãy cho chúng tôi xem mã hoàn chỉnh -

Ví dụ

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args){
      var subjects = new List();
      subjects.Add("Physics");
      subjects.Add("Chemistry");
      subjects.Add("Biology");
      subjects.Add("Science");

      Console.WriteLine("ELEMENTS:");
      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }

      // remove element at 3rd position
      subjects.RemoveAt(2);
      Console.WriteLine("After removing an element:");

      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }
   }
}

Đầu ra

ELEMENTS:
Physics
Chemistry
Biology
Science
After removing an element:
Physics
Chemistry
Science