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

Phương thức UnionWith trong C#

Sử dụng phương thức UnionWith trong C# để lấy hợp집 hợp (các phần tử duy nhất) từ hai tập hợp.

Giả sử có hai Dictionary:

Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);

Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("pen", 3);

Sử dụng HashSet và UnionWith để lấy hợp집 hợp các key:

HashSet<string> hSet = new HashSet<string>(dict1.Keys);
hSet.UnionWith(dict2.Keys);

Ví dụ hoàn chỉnh

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary<string, int> dict1 = new Dictionary<string, int>();
        dict1.Add("pencil", 1);
        dict1.Add("pen", 2);
        
        Dictionary<string, int> dict2 = new Dictionary<string, int>();
        dict2.Add("pen", 3);
        
        HashSet<string> hSet = new HashSet<string>(dict1.Keys);
        hSet.UnionWith(dict2.Keys);
        
        Console.WriteLine("Dictionary đã gộp...");
        foreach (string val in hSet)
        {
            Console.WriteLine(val);
        }
    }
}

Kết quả

Dictionary đã gộp...
pencil
pen

Giải thích: UnionWith sửa đổi HashSet hiện tại để chứa tất cả phần tử từ cả hai tập hợp, tự động loại bỏ trùng lặp. Chỉ lấy Key của Dictionary, không quan tâm Value.