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 clone a generic list in C#?
A list is a Generic collection to hold elements of same datatypes.
To clone a list, you can use the CopyTo method.
Declare a list and add elements −
List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");
Now create a new array and clone the list into it −
string[] arr = new string[10]; myList.CopyTo(arr);
Here is the complete code −
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");
Console.WriteLine("First list...");
foreach(string value in myList) {
Console.WriteLine(value);
}
string[] arr = new string[10];
myList.CopyTo(arr);
Console.WriteLine("After cloning...");
foreach(string value in arr) {
Console.WriteLine(value);
}
}
}
Output
First list... Programming Web Dev Database After cloning... Programming Web Dev Database
Advertisements