ListDictionary.CopyTo() मेथड लिस्ट डिक्शनरी के की-वैल्यू पेयर्स को DictionaryEntry ऐरे में कॉपी करता है। ListDictionary छोटे डेटा सेट के लिए ऑप्टिमाइज़्ड लिंक्ड-लिस्ट आधारित डिक्शनरी है।
उदाहरण 1: सटीक आकार के ऐरे में कॉपी (इंडेक्स 0)
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
ListDictionary dict = new ListDictionary();
dict.Add(1, "Harry");
dict.Add(2, "Mark");
dict.Add(3, "John");
dict.Add(4, "Jacob");
dict.Add(5, "Tim");
dict.Add(6, "Sam");
dict.Add(7, "Tom");
dict.Add(8, "Kevin");
Console.WriteLine("ListDictionary तत्व (इंसर्शन क्रम)...");
foreach (DictionaryEntry entry in dict) {
Console.WriteLine(entry.Key + " " + entry.Value);
}
// Count आकार का ऐरे
DictionaryEntry[] dictArr = new DictionaryEntry[dict.Count];
// इंडेक्स 0 से कॉपी करें
dict.CopyTo(dictArr, 0);
Console.WriteLine("\nऐरे इंस्टेंस में कॉपी (इंसर्शन क्रम में)...");
for (int i = 0; i < dictArr.Length; i++) {
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
}
आउटपुट
ListDictionary तत्व (इंसर्शन क्रम)...
1 Harry
2 Mark
3 John
4 Jacob
5 Tim
6 Sam
7 Tom
8 Kevin
ऐरे इंस्टेंस में कॉपी (इंसर्शन क्रम में)...
Key = 1, Value = Harry
Key = 2, Value = Mark
Key = 3, Value = John
Key = 4, Value = Jacob
Key = 5, Value = Tim
Key = 6, Value = Sam
Key = 7, Value = Tom
Key = 8, Value = Kevin
उदाहरण 2: बड़े ऐरे में ऑफसेट के साथ कॉपी
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
ListDictionary dict = new ListDictionary();
dict.Add(1, "Harry");
dict.Add(2, "Mark");
dict.Add(3, "John");
dict.Add(4, "Jacob");
dict.Add(5, "Tim");
Console.WriteLine("ListDictionary तत्व...");
foreach (DictionaryEntry entry in dict) {
Console.WriteLine(entry.Key + " " + entry.Value);
}
// 10 आकार का ऐरे, इंडेक्स 5 से कॉपी करें
DictionaryEntry[] dictArr = new DictionaryEntry[10];
dict.CopyTo(dictArr, 5);
Console.WriteLine("\nऐरे इंस्टेंस में कॉपी (इंडेक्स 5 से, इंसर्शन क्रम)...");
for (int i = 0; i < dictArr.Length; i++) {
Console.WriteLine("Key = " + dictArr[i].Key + ", Value = " + dictArr[i].Value);
}
}
}
आउटपुट
ListDictionary तत्व...
1 Harry
2 Mark
3 John
4 Jacob
5 Tim
ऐरे इंस्टेंस में कॉपी (इंडेक्स 5 से, इंसर्शन क्रम)...
Key = , Value =
Key = , Value =
Key = , Value =
Key = , Value =
Key = , Value =
Key = 1, Value = Harry
Key = 2, Value = Mark
Key = 3, Value = John
Key = 4, Value = Jacob
Key = 5, Value = Tim
ListDictionary बनाम OrderedDictionary कॉपी क्रम
| क्लास | foreach क्रम | CopyTo क्रम |
|---|---|---|
| ListDictionary | इंसर्शन क्रम | इंसर्शन क्रम (समान) |
| OrderedDictionary | इंसर्शन क्रम | रिवर्स इंसर्शन क्रम |
मुख्य बिंदु
- ListDictionary छोटे संग्रह (आमतौर पर ≤ 10 आइटम) के लिए कुशल है।
- CopyTo इंसर्शन क्रम बनाए रखता है (OrderedDictionary के विपरीत)।
- लक्ष्य ऐरे:
DictionaryEntry[]। - लीगेसी क्लास: नए कोड के लिए
Dictionary<TKey, TValue>उपयोग करें। - आंतरिक रूप से सिंगली लिंक्ड लिस्ट का उपयोग करता है।