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

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

Giới thiệu

Để xóa một phần tử cụ thể khỏi HashSet<T>, bạn sử dụng phương thức Remove(T). Phương thức trả về true nếu phần tử tồn tại và được xóa, ngược lại trả về false. HashSet không cho phép phần tử trùng lặp.

Ví dụ 1: Xóa từ HashSet chứa chuỗi

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        HashSet<string> set1 = new HashSet<string>();
        set1.Add("AB");
        set1.Add("CD");
        set1.Add("EF");
        set1.Add("AB"); // Trùng lặp, bị bỏ qua
        set1.Add("IJ");
        set1.Add("KL");
        set1.Add("EF"); // Trùng lặp
        set1.Add("OP");

        Console.WriteLine("Các phần tử trong HashSet1");
        foreach (string val in set1)
            Console.WriteLine(val);

        HashSet<string> set2 = new HashSet<string>();
        set2.Add("EF");
        set2.Add("KL");

        Console.WriteLine("Các phần tử trong HashSet2");
        foreach (string val in set2)
            Console.WriteLine(val);

        Console.WriteLine("Số lượng phần tử trong HashSet2 = " + set2.Count);

        set2.Remove("KL");

        Console.WriteLine("\nCác phần tử trong HashSet2... (ĐÃ CẬP NHẬT)");
        foreach (string res in set2)
            Console.WriteLine(res);

        Console.WriteLine("Số lượng phần tử trong HashSet2 (Đã cập nhật) = " + set2.Count);
        Console.WriteLine("\nset1 có phải siêu tập của set2 không? " + set1.IsSupersetOf(set2));
    }
}

Kết quả

Các phần tử trong HashSet1
AB
CD
EF
IJ
KL
OP
Các phần tử trong HashSet2
EF
KL
Số lượng phần tử trong HashSet2 = 2
Các phần tử trong HashSet2... (ĐÃ CẬP NHẬT)
EF
Số lượng phần tử trong HashSet2 (Đã cập nhật) = 1
set1 có phải siêu tập của set2 không? True

Ví dụ 2: Xóa từ HashSet chứa số nguyên

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        HashSet<int> set1 = new HashSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        set1.Add(400);
        set1.Add(500);
        set1.Add(600);

        Console.WriteLine("Các phần tử trong HashSet");
        foreach (int val in set1)
            Console.WriteLine(val);

        Console.WriteLine("Số lượng phần tử trong HashSet = " + set1.Count);

        set1.Remove(300);

        Console.WriteLine("\nCác phần tử trong HashSet... (ĐÃ CẬP NHẬT)");
        foreach (int res in set1)
            Console.WriteLine(res);

        Console.WriteLine("Số lượng phần tử trong HashSet (Đã cập nhật) = " + set1.Count);
    }
}

Kết quả

Các phần tử trong HashSet
100
200
300
400
500
600
Số lượng phần tử trong HashSet = 6
Các phần tử trong HashSet... (ĐÃ CẬP NHẬT)
100
200
400
500
600
Số lượng phần tử trong HashSet (Đã cập nhật) = 5

Lưu ý: HashSet<T> cung cấp hiệu suất O(1) cho các thao tác thêm, xóa, tìm kiếm. Thứ tự phần tử không được đảm bảo.