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

Xóa phần tử chỉ định khỏi List trong C#

Giới thiệu

Phương thức Remove(T item) của List<T> xóa phần tử đầu tiên khớp với giá trị cho trước. Trả về true nếu xóa thành công, false nếu không tìm thấy.

Ví dụ 1: Xóa chuỗi khỏi List

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        List list1 = new List();
        list1.Add("One");
        list1.Add("Two");
        list1.Add("Three");
        list1.Add("Four");
        list1.Add("Five");

        Console.WriteLine("Các phần tử trong List1...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }

        List list2 = new List();
        list2.Add("India");
        list2.Add("US");
        list2.Add("UK");
        list2.Add("Canada");
        list2.Add("Poland");
        list2.Add("Netherlands");

        Console.WriteLine("Các phần tử trong List2...");
        foreach (string res in list2)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("\nList2 bằng List1? = " + list2.Equals(list1));
        Console.WriteLine("\nSố phần tử list2 = " + list2.Count);

        list2.Remove("US");

        Console.WriteLine("\nSố phần tử list2 (cập nhật) = " + list2.Count);
        Console.WriteLine("Các phần tử trong List2... CẬP NHẬT");
        foreach (string res in list2)
        {
            Console.WriteLine(res);
        }
    }
}

Kết quả

Các phần tử trong List1...
One
Two
Three
Four
Five
Các phần tử trong List2...
India
US
UK
Canada
Poland
Netherlands
List2 bằng List1? = False
Số phần tử list2 = 6
Số phần tử list2 (cập nhật) = 5
Các phần tử trong List2... CẬP NHẬT
India
UK
Canada
Poland
Netherlands

Ví dụ 2: Xóa số nguyên

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        List list = new List();
        list.Add(5);
        list.Add(10);
        list.Add(20);
        list.Add(50);
        list.Add(75);
        list.Add(100);

        Console.WriteLine("Các phần tử trong List...");
        foreach (int res in list)
        {
            Console.WriteLine(res);
        }

        Console.WriteLine("\nSố phần tử trong list = " + list.Count);
        list.Remove(50);
        Console.WriteLine("\nSố phần tử trong list (cập nhật) = " + list.Count);
        Console.WriteLine("Các phần tử trong List... CẬP NHẬT");
        foreach (int res in list)
        {
            Console.WriteLine(res);
        }
    }
}

Kết quả

Các phần tử trong List...
5
10
20
50
75
100
Số phần tử trong list = 6
Số phần tử trong list (cập nhật) = 5
Các phần tử trong List... CẬP NHẬT
5
10
20
75
100

Các phương thức xóa khác

  • RemoveAt(int index) – xóa tại vị trí index.
  • RemoveAll(Predicate<T>) – xóa tất cả phần tử thỏa điều kiện.
  • Clear() – xóa toàn bộ.