Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

둘 이상의 사전의 합집합을 찾는 C# 프로그램

<시간/>

먼저 두 사전을 모두 설정하십시오 -

Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("water", 1);
dict1.Add("food", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("clothing", 3);
dict2.Add("shelter", 4);

이제 HashSet을 만들고 UnionsWith() 메서드를 사용하여 위의 twoDictionaries 간의 합집합을 찾습니다. -

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

다음은 완전한 코드입니다 -

예시

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      Dictionary < string, int > dict1 = new Dictionary < string, int > ();
      dict1.Add("water", 1);
      dict1.Add("food", 2);

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

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

      Console.WriteLine("Union of Dictionary...");
      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}

출력

Union of Dictionary...
water
food
clothing
shelter