Collection<T>.CopyTo(T[] array, int index) মেথড ব্যবহার করে কালেকশনের উপাদানগুলো একটি অ্যারের নির্দিষ্ট সূচক থেকে কপি করা যায়। Collection<T> একটি বেস ক্লাস যা কাস্টম কালেকশন তৈরির জন্য ব্যবহার করা হয়।
উদাহরণ ১: অফসেট ২ সহ কপি
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);
}
string[] strArr = new string[10];
col.CopyTo(strArr, 2); // সূচক ২ থেকে শুরু
Console.WriteLine("\nArray...");
foreach(string str in strArr) {
Console.WriteLine(str);
}
}
}
আউটপুট
Collection.... One Two Three Four Five Six Seven Eight Array... One Two Three Four Five Six Seven Eight
নোট: আউটপুটে অ্যারের প্রথম দুটি উপাদান null/empty দেখানো উচিত ছিল, কিন্তু প্রদত্ত আউটপুটে সেটি অনুপস্থিত।
উদাহরণ ২: অফসেট ৩ সহ কপি (ছোট কালেকশন)
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);
}
string[] strArr = new string[10];
col.CopyTo(strArr, 3); // সূচক ৩ থেকে শুরু
Console.WriteLine("\nArray...");
foreach(string str in strArr) {
Console.WriteLine(str);
}
}
}
আউটপুট
Collection.... One Two Three Four Five Array... One Two Three Four Five
দ্রষ্টব্য: দ্বিতীয় উদাহরণের আউটপুটে অফসেট ৩-এর প্রভাব দেখানো হয়নি (প্রথম ৩টি null হওয়া উচিত)। CopyTo-র সময় লক্ষ্য অ্যারেতে পর্যাপ্ত জায়গা থাকতে হবে, অন্যথায় ArgumentException হবে।