

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Copying the Collection elements to an array in C#
To copy the Collection elements to an array, the code is as follows −
Example
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); } } }
Output
This will produce the following output −
Collection.... One Two Three Four Five Six Seven Eight Array... One Two Three Four Five Six Seven Eight
Example
Let us now see another example −
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); } } }
Output
This will produce the following output −
Collection.... One Two Three Four Five Array... One Two Three Four Five
- Related Questions & Answers
- Copying BitArray elements to an Array in C#
- Copying the Hashtable elements to an Array Instance in C#
- Copying the SortedList elements to an Array Object in C#
- Copying the Queue elements to one-dimensional array in C#
- Copying the elements of ArrayList to a new array in C#
- Copying the HybridDictionary entries to an Array Instance in C#
- What are the different ways of copying an array into another array in Java?
- How to copy a List collection to an array?
- How to retain elements from a Collection in another Collection
- How to remove all elements from a Collection in another Collection
- C Program to delete the duplicate elements in an array
- C program to find the unique elements in an array.
- Add elements to LinkedHashMap collection in Java
- Can you assign an Array of 100 elements to an array of 10 elements in Java?
- Remove all elements from the Collection in C#
Advertisements