Hashtable.CopyTo() मेथड हैशटेबल के की-वैल्यू पेयर्स को DictionaryEntry ऐरे में कॉपी करता है। चूंकि Hashtable अनऑर्डर्ड है, कॉपी क्रम अनिर्धारित होता है।
उदाहरण 1: सटीक आकार के ऐरे में इंडेक्स 0 से कॉपी
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add("1", "AB");
hash.Add("2", "CD");
hash.Add("3", "EF");
hash.Add("4", "GH");
hash.Add("5", "IJ");
Console.WriteLine("Hashtable की और वैल्यू पेयर्स...");
foreach (DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
// Count आकार का ऐरे, इंडेक्स 0 से कॉपी
DictionaryEntry[] dictArr = new DictionaryEntry[hash.Count];
hash.CopyTo(dictArr, 0);
Console.WriteLine("\nऐरे इंस्टेंस में कॉपी किया गया...");
for (int i = 0; i < dictArr.Length; i++) {
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
}
आउटपुट
Hashtable की और वैल्यू पेयर्स...
1 and AB
2 and CD
3 and EF
4 and GH
5 and IJ
ऐरे इंस्टेंस में कॉपी किया गया...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
उदाहरण 2: बड़े ऐरे में इंडेक्स 2 से कॉपी
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable(5);
hash.Add("1", "AB");
hash.Add("2", "CD");
Console.WriteLine("Hashtable की और वैल्यू पेयर्स...");
foreach (DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
}
// 5 आकार का ऐरे, इंडेक्स 2 से कॉपी
DictionaryEntry[] dictArr = new DictionaryEntry[5];
hash.CopyTo(dictArr, 2);
Console.WriteLine("\nऐरे इंस्टेंस में कॉपी किया गया (इंडेक्स 2 से)...");
for (int i = 0; i < dictArr.Length; i++) {
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
}
आउटपुट
Hashtable की और वैल्यू पेयर्स...
1 and AB
2 and CD
ऐरे इंस्टेंस में कॉपी किया गया (इंडेक्स 2 से)...
Key = , Value =
Key = , Value =
Key = 1, Value = AB
Key = 2, Value = CD
Key = , Value =
महत्वपूर्ण नोट्स
CopyTo(Array, index)- ऐरेDictionaryEntry[]होना चाहिए।- Hashtable में क्रम गारंटीड नहीं है - कॉपी क्रम भी अनिर्धारित है।
- लक्ष्य ऐरे में पर्याप्त जगह होनी चाहिए (index + Count ≤ Length)।
DictionaryEntryएक स्ट्रक्चर है जिसमेंKeyऔरValueप्रॉपर्टीज़ होती हैं।