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

Chương trình C# kết hợp khóa của hai Dictionary

Sử dụng HashSet<string> và UnionWith để hợp nhất tập khóa từ hai Dictionary.

Ví dụ

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary dict1 = new Dictionary();
        dict1.Add("one", 1);
        dict1.Add("Two", 2);

        Dictionary dict2 = new Dictionary();
        dict2.Add("Three", 3);
        dict2.Add("Four", 4);

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

        Console.WriteLine("Hợp nhất khóa Dictionary...");
        foreach (string val in hSet)
            Console.WriteLine(val);
    }
}

Kết quả

Hợp nhất khóa Dictionary...
one
Two
Three
Four

Lưu ý: HashSet tự động loại bỏ khóa trùng lặp. Thứ tự không được bảo đảm.