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

Phương thức Add, Remove trong List C#

List<T> là collection generic trong C#. Dùng Add() và Remove() để thêm/xóa phần tử.

Ví dụ Add()

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);
    }
}

Kết quả

Football Tennis Soccer

Ví dụ Remove()

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");
        Console.WriteLine("Danh sách cũ...");
        foreach (string s in sports) Console.WriteLine(s);
        Console.WriteLine("Danh sách mới...");
        sports.Remove("Tennis");
        foreach (string s in sports) Console.WriteLine(s);
    }
}

Kết quả

Danh sách cũ... Football Tennis Soccer
Danh sách mới... Football Soccer