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 < 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