HashSet और UnionWith से यूनियन प्राप्त करना
C# में UnionWith मेथड का उपयोग दो कलेक्शंस से यूनियन (अद्वितीय एलिमेंट्स) प्राप्त करने के लिए किया जाता है।
मान लीजिए हमारे पास दो डिक्शनरी हैं:
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 और UnionWith का उपयोग करके यूनियन प्राप्त करें:
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("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("Merged Dictionary...");
foreach(string val in hSet) {
Console.WriteLine(val);
}
}
}
आउटपुट
Merged Dictionary... pencil pen
व्याख्या: दोनों डिक्शनरीज की कीज़ (keys) का यूनियन लिया गया है। "pen" दोनों में मौजूद है, लेकिन HashSet में केवल एक बार आता है क्योंकि यह डुप्लिकेट्स को हटा देता है।