Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
How to copy collection to Array using C#?
To copy a collection to an array, firstly set it −
List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motorbike");
list1.Add("Train");
Now declare a string array and use the CopyTo() method to copy −
string[] arr = new string[20]; list1.CopyTo(arr);
Let us see the complete code to copy collection to array −
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
List < string > list1 = new List < string > ();
list1.Add("Car");
list1.Add("Bus");
list1.Add("Motobike");
list1.Add("Train");
Console.WriteLine("First list...");
foreach(string value in list1) {
Console.WriteLine(value);
}
string[] arr = new string[20];
list1.CopyTo(arr);
Console.WriteLine("After copy...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
}Advertisements