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

Phương thức Thêm, Loại bỏ trong danh sách C # là gì?

Danh sách là một tập hợp trong C # và là một tập hợp chung. Các phương thức thêm và xóa được sử dụng trong danh sách C # để thêm và xóa các phần tử.

Hãy để chúng tôi xem cách sử dụng phương thức Add () trong C #.

Ví dụ

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football");
      sports.Add("Tennis");
      sports.Add("Soccer");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

Đầu ra

Football
Tennis
Soccer

Hãy để chúng tôi xem cách sử dụng phương thức Remove () trong C #.

Ví dụ

using System;
using System.Collections.Generic;
class Program {
   static void Main() {
      List<string> sports = new List<string>();
      sports.Add("Football"); // add method
      sports.Add("Tennis");
      sports.Add("Soccer");
      Console.WriteLine("Old List...");
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
      Console.WriteLine("New List...");
      sports.Remove("Tennis"); // remove method
      foreach (string s in sports) {
         Console.WriteLine(s);
      }
   }
}

Đầu ra

Old List...
Football
Tennis
Soccer
New List...
Football
Soccer