Collection<T> क्लास (System.Collections.ObjectModel) एक जेनेरिक संग्रह बेस क्लास है। इसका CopyTo() मेथड तत्वों को एक-आयामी ऐरे में निर्दिष्ट इंडेक्स से कॉपी करता है।
उदाहरण 1: इंडेक्स 2 से कॉपी करना
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Three");
col.Add("Four");
col.Add("Five");
col.Add("Six");
col.Add("Seven");
col.Add("Eight");
Console.WriteLine("Collection...");
foreach (string str in col) {
Console.WriteLine(str);
}
// 10 आकार का ऐरे, इंडेक्स 2 से कॉपी करें
string[] strArr = new string[10];
col.CopyTo(strArr, 2);
Console.WriteLine("\nऐरे (इंडेक्स 2 से कॉपी)...");
foreach (string str in strArr) {
Console.WriteLine(str ?? "(null)");
}
}
}
आउटपुट
Collection...
One
Two
Three
Four
Five
Six
Seven
Eight
ऐरे (इंडेक्स 2 से कॉपी)...
(null)
(null)
One
Two
Three
Four
Five
Six
Seven
Eight
उदाहरण 2: इंडेक्स 3 से कॉपी करना (छोटा संग्रह)
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Three");
col.Add("Four");
col.Add("Five");
Console.WriteLine("Collection...");
foreach (string str in col) {
Console.WriteLine(str);
}
// 10 आकार का ऐरे, इंडेक्स 3 से कॉपी करें
string[] strArr = new string[10];
col.CopyTo(strArr, 3);
Console.WriteLine("\nऐरे (इंडेक्स 3 से कॉपी)...");
foreach (string str in strArr) {
Console.WriteLine(str ?? "(null)");
}
}
}
आउटपुट
Collection...
One
Two
Three
Four
Five
ऐरे (इंडेक्स 3 से कॉपी)...
(null)
(null)
(null)
One
Two
Three
Four
Five
(null)
(null)
मुख्य बिंदु
Collection<T>.CopyTo(T[], int)- प्रकार-सुरक्षित ऐरे कॉपी।- लक्ष्य ऐरे उसी प्रकार
Tका होना चाहिए (object[] नहीं)। - इंडेक्स पैरामीटर लक्ष्य ऐरे में प्रारंभिक स्थिति है।
- यदि
index + Count > array.LengthतोArgumentExceptionफेंका जाता है। Collection<T>कस्टम संग्रह बनाने के लिए बेस क्लास के रूप में डिज़ाइन किया गया है।
Collection<T> बनाम List<T>
| विशेषता | Collection<T> | List<T> |
|---|---|---|
| वर्चुअल मेथड्स | हां (ओवरराइड योग्य) | नहीं |
| प्रदर्शन | थोड़ा धीमा | तेज़ |
| उपयोग | कस्टम संग्रह बेस | सामान्य-उद्देश्य लिस्ट |