{"id":81588,"date":"2023-02-08T08:34:27","date_gmt":"2023-02-08T07:34:27","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=81588"},"modified":"2023-02-09T09:13:06","modified_gmt":"2023-02-09T08:13:06","slug":"csharp-how-to-clone-a-list","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/","title":{"rendered":"How to Clone a List in C#?"},"content":{"rendered":"<p>In this article, we will look at all the different ways we can clone a List in C# to another and what we should pay attention to when doing so.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/collections-lists\/HowToCloneAList\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>In C# we have ample ways of doing that, so let&#8217;s dive right in.<\/p>\n<h2><a id=\"CloningListThatContainsValueTypes\"><\/a>How to Clone a List in C# That Contains Value Types<\/h2>\n<p>A <a href=\"https:\/\/code-maze.com\/csharp-list-collection\/\" target=\"_blank\" rel=\"noopener\">List&lt;T&gt;<\/a>, which contains value types, is easy to clone as <strong>value types directly contain an instance of their type<\/strong>.\u00a0<\/p>\n<p>As we all love pizza, we are going to be cloning a list of toppings with all the methods in this section. <strong>Now, we are going to use a string in the example even though it is not a value type but a reference type. On the other hand, it is immutable and behaves as a value type, <\/strong>so we can use it in this section:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppings = new List&lt;string&gt;\r\n{\r\n    \"Mozzarella\",\r\n    \"Olive oil\",\r\n    \"Basil\"\r\n};<\/pre>\n<p>Here, we define a <code>toppings<\/code> variable of <code>List&lt;string&gt;<\/code> type, that holds the toppings for the classic Margherita pizza.<\/p>\n<p>Next, we&#8217;ll look at the options for cloning the values of that <code>List&lt;string&gt;<\/code> to another.<\/p>\n<h3><a id=\"UsingListConstructor\"><\/a>Using the List\u2019s Constructor<\/h3>\n<p>One of the overloads of the <code>List&lt;T&gt;<\/code>&#8216;s constructor takes in an <code>IEnumerable&lt;T&gt;<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithConstructor = new List&lt;string&gt;(toppings);<\/code><\/p>\n<p>Here, we initialize a new <code>toppingsClonedWithConstructor<\/code> variable that contains the copied elements from our <code>toppings<\/code> list.<\/p>\n<h3><a id=\"UsingListCopyToMethod\"><\/a>Using the List\u2019s CopyTo Method<\/h3>\n<p><code>List&lt;T&gt;<\/code> has several methods that we can use to clone its contents to another list or collection.<\/p>\n<p>One of those is the <code>CopyTo<\/code> method. The list inherits it from the <code>ICollection&lt;T&gt;<\/code> interface and it can be used to clone the <code>List&lt;T&gt;<\/code> to a <code>T[]<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithCopyTo = new string[toppings.Count];\r\ntoppings.CopyTo(toppingsClonedWithCopyTo);<\/pre>\n<p>First, we initialize a <code>toppingsClonedWithCopyTo<\/code> variable as a <code>string[]<\/code> that has a length equal to the length of the <code>toppings<\/code> list &#8211; hence the <code>toppings.Count<\/code>. Then we use the <code>CopyTo<\/code> method on the <code>toppings<\/code> list and pass the newly initialized array as a parameter. This way its contents are copied over to <code>toppingsClonedWithCopyTo<\/code>.<\/p>\n<h3><a id=\"UsingListAddRangeMethod\"><\/a>Using the List\u2019s AddRange Method<\/h3>\n<p>Another method that takes in an <code>IEnumerable&lt;T&gt;<\/code> as a parameter is the <code>AddRange<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithAddRange = new List&lt;string&gt;();\r\ntoppingsClonedWithAddRange.AddRange(toppings);<\/pre>\n<p>The <code>AddRange<\/code> method needs a <code>List&lt;T&gt;<\/code> that is already initialized, so we declare the <code>toppingsClonedWithAddRange<\/code> variable and assign an empty <code>List&lt;string&gt;<\/code> to it. Then we pass the <code>toppings<\/code> as a parameter to the <code>AddRange<\/code> method and it clones the contents for us.<\/p>\n<h3><a id=\"UsingEnumerableToListMethod\"><\/a>Using the Enumerable&#8217;s ToList Method<\/h3>\n<p>The <code>System.Linq<\/code> namespace provides us with the <code>Enumerable.ToList<\/code> method:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithToList = toppings.ToList();<\/code><\/p>\n<p>Here, we directly initialize our <code>toppingsClonedWithToList<\/code> variable by calling the <code>ToList<\/code> method on our already existing <code>toppings<\/code> variable, which clones its contents to our new list.<\/p>\n<p>Alternatively, we can use the <code>Enumerable.ToArray<\/code> method in the same way if we want to clone the contents of a <code>List&lt;T&gt;<\/code> to <code>T[]<\/code>.<\/p>\n<h3><a id=\"UsingConvertAllMethod\"><\/a>Using the ConvertAll Method<\/h3>\n<p><code>List&lt;T&gt;<\/code> has another useful method that might look a bit daunting on the surface &#8211; this is the <code>ConvertAll&lt;TOutput&gt;(Converter&lt;T, TOutput&gt;)<\/code> method. It converts all the members of a list from one type to another and returns a list containing the converted members. We can even use it for cloning:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithConvertAll = toppings\r\n    .ConvertAll(new Converter&lt;string, string&gt;(x =&gt; x));<\/pre>\n<p>We start by initializing a <code>toppingsClonedWithConvertAll<\/code> variable and assigning it the value returned from using the <code>ConvertAll<\/code> method on our <code>toppings<\/code> list. The method takes in a\u00a0<code>Converter&lt;TInput, TOutput&gt;<\/code>, which is just a delegate for a method that converts an element from one type to another. It takes in the name of a method used for the conversion, or we can pass an anonymous method as well.<\/p>\n<p>We don&#8217;t need a separate method to convert the element we pass in, so we simply use a lambda expression that returns the same value, hence the <code>x =&gt; x<\/code>.<\/p>\n<h3><a id=\"UsingICloneableInterface\"><\/a>Using the ICloneable Interface<\/h3>\n<p>A bit more complex way of cloning a <code>List&lt;T&gt;<\/code> can be achieved using the <code>ICloneable<\/code> interface. But before we can use the interface&#8217;s <code>Clone<\/code> method, we need to set things up:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class ToppingsList&lt;T&gt; : List&lt;T&gt;, ICloneable\r\n{\r\n    public object Clone()\r\n    {\r\n        return this.MemberwiseClone();\r\n    }\r\n}<\/pre>\n<p>We create a generic <code>ToppingsList&lt;T&gt;<\/code> class in a new file that inherits <code>List&lt;T&gt;<\/code> and <code>ICloneable<\/code>. We also implement the <code>Clone<\/code> method by just returning the result of the <code>Object<\/code>&#8216;s (the ultimate base class in .NET) <code>MemberwiseClone<\/code> method which gives us a shallow copy of the object.<\/p>\n<p>Once we have done that, we go back to our <code>Program<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var customToppingsList = new ToppingsList&lt;string&gt;\r\n{\r\n    \"Mozzarella\",\r\n    \"Olive oil\",\r\n    \"Basil\"                \r\n};<\/pre>\n<p>With this, we create a <code>customToppingsList<\/code> variable of our new generic type as <code>ToppingsList&lt;string&gt;<\/code> and initialize it like a regular <code>List&lt;string&gt;<\/code>.\u00a0<\/p>\n<p>Then we continue with:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toppingsClonedWithICloneable = (ToppingsList&lt;string&gt;)customToppingsList.Clone();<\/code><\/p>\n<p>We declare a <code>toppingsClonedWithICloneable<\/code> variable and use the <code>Clone<\/code> method on our <code>customToppingsList<\/code>. We also cast the result to <code>ToppingsList&lt;string&gt;<\/code> as the method itself returns an <code>object<\/code>.<\/p>\n<p>To make sure that everything we have done to clone a List containing value types in C# works as intended, we can print all the results on the console:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine(\"Original list: \" + string.Join(\", \", toppings));\r\nConsole.WriteLine(\"Cloned with Constructor: \" + string.Join(\", \", toppingsClonedWithConstructor));\r\nConsole.WriteLine(\"Cloned with CopyTo: \" + string.Join(\", \", toppingsClonedWithCopyTo));\r\nConsole.WriteLine(\"Cloned with AddRange: \" + string.Join(\", \", toppingsClonedWithAddRange));\r\nConsole.WriteLine(\"Cloned with ToList: \" + string.Join(\", \", toppingsClonedWithToList));\r\nConsole.WriteLine(\"Cloned with ConverAll: \" + string.Join(\", \", toppingsClonedWithConvertAll));\r\nConsole.WriteLine(\"Cloned with ICloneable: \" + string.Join(\", \", toppingsClonedWithICloneable));<\/pre>\n<p>And check the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Original list: Mozzarella, Olive oil, Basil\r\nCloned with Constructor: Mozzarella, Olive oil, Basil\r\nCloned with CopyTo: Mozzarella, Olive oil, Basil\r\nCloned with AddRange: Mozzarella, Olive oil, Basil\r\nCloned with ToList: Mozzarella, Olive oil, Basil\r\nCloned with ConverAll: Mozzarella, Olive oil, Basil\r\nCloned with ICloneable: Mozzarella, Olive oil, Basil<\/pre>\n<h2><a id=\"CloningListThatContainsReferenceTypes\"><\/a>How to Clone a List in C# That Contains Reference Types<\/h2>\n<p><strong>Reference type variables, unlike value type ones, store a reference to the data and not the data itself<\/strong>. This means that when we work with reference types, two variables can reference the same data &#8211; the downside here is that <strong>operations on one variable can affect the data referenced by another<\/strong>.\u00a0<\/p>\n<p>Building on the pizza trend from earlier, let&#8217;s expand on our example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Pizza\r\n{\r\n    public string Name { get; set; }\r\n    public List&lt;string&gt; Toppings { get; set; }\r\n\r\n    public override string ToString()\r\n    {\r\n        return $\"Pizza name: {Name}; Toppings: {string.Join(\", \", Toppings)}\";\r\n    }\r\n}<\/pre>\n<p>In a separate file, we declare a <code>Pizza<\/code> class with two simple properties &#8211; <code>Name<\/code> and <code>Toppings<\/code>. We also override the <code>ToString<\/code> method for easy visualization.\u00a0<\/p>\n<p>We are cloning lists, so we need one with reference types:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var pizzas = new List&lt;Pizza&gt;\r\n{\r\n    new Pizza\r\n    {\r\n        Name= \"Margherita\",\r\n        Toppings = new List&lt;string&gt;\r\n        {\r\n            \"Mozzarella\",\r\n            \"Olive oil\",\r\n            \"Basil\"\r\n        }\r\n    },\r\n    new Pizza\r\n    {\r\n        Name= \"Diavola\",\r\n        Toppings = new List&lt;string&gt;\r\n        {\r\n            \"Mozzarella\",\r\n            \"Ventricina\",\r\n            \"Chili peppers\"\r\n        }\r\n    }\r\n};<\/pre>\n<p>Here we declare a <code>pizzas<\/code> variable of type <code>List&lt;Pizza&gt;<\/code> and add two pizzas to it.<\/p>\n<p>Now, let&#8217;s look into the two types of copying we have when dealing with reference types.<\/p>\n<h3><a id=\"ShallowCopy\"><\/a>Shallow Copy<\/h3>\n<p>We can easily achieve a shallow copy of our <code>pizzas<\/code> list with any of the methods from the previous section. But <strong>a shallow copy of a <code>List&lt;T&gt;<\/code>, where <code>T<\/code> is a reference type, copies only the structure of the collection and references to its elements, not the elements themselves<\/strong>. This means that changes to the elements in any of the two lists will be reflected in both the original and copied lists.<\/p>\n<p>Let&#8217;s illustrate this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var clonedPizzas = pizzas.ToList();\r\n\r\nvar margherita = pizzas\r\n    .FirstOrDefault(x =&gt; x.Name == \"Margherita\");\r\n\r\nmargherita.Toppings.Clear();<\/pre>\n<p>First, we create a <code>clonedPizzas<\/code> variable and clone the contents of <code>pizzas<\/code> to it using the <code>ToList<\/code> method (using any of the other methods used earlier will produce the same result). Then we get the Margherita pizza from the original list using the <code>FirstOrDefault<\/code> method. Finally, we use the <code>Clear<\/code> method to empty the list of <code>Toppings<\/code> for that pizza.<\/p>\n<p>Now, let&#8217;s see what happens:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Console.WriteLine($\"Original Margherita: {pizzas.First()}\");\r\nConsole.WriteLine($\"Cloned with ToList: {clonedPizzas.First()}\");<\/pre>\n<p>We print the first pizza of each list to the console, which in both cases is the Margherita, using the <code>First<\/code> method.<\/p>\n<p>We overrode the <code>ToString<\/code> method which will give us an easy-to-read representation of each pizza. Now, we can check the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Original Margherita: Pizza name: Margherita; Toppings:\r\nCloned with ToList: Pizza name: Margherita; Toppings:<\/pre>\n<p>We can see that both the original and copied Margherita pizzas now have an empty list of <code>Toppings<\/code>. This is because when creating a shallow copy, we only clone the references to the objects, not the actual objects. This is not ideal because when we change elements in one list, we change the elements everywhere we have copied that list.<\/p>\n<p>This might cause serious problems for us, so let&#8217;s what we can do to prevent it.<\/p>\n<h3><a id=\"DeepCopy\"><\/a>Deep Copy\u00a0<\/h3>\n<p>The alternative is to create<strong> a<\/strong> <strong>deep copy<\/strong> &#8211; this <strong>means that<\/strong> <strong>we don&#8217;t just copy the references to the objects but create new, copied objects<\/strong>. This produces a different result than shallow copies as<strong> the objects referenced by the copied list are separate from those referenced in the original list<\/strong>.<\/p>\n<h3><a id=\"UsingICloneableInterface\"><\/a>Clone a List Using the ICloneable Interface<\/h3>\n<p>We can also use the <code>Clone<\/code> method we get from inheriting the <code>ICloneable<\/code> interface to create a deep copy.<\/p>\n<p>Let&#8217;s do the necessary updates:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"1,6-13\">public class Pizza : ICloneable\r\n{\r\n    public string Name { get; set; }\r\n    public List&lt;string&gt; Toppings { get; set; }\r\n\r\n    public object Clone()\r\n    {\r\n        return new Pizza\r\n        {\r\n            Name = Name,\r\n            Toppings = Toppings.ToList(),\r\n        };\r\n    }\r\n\r\n    public override string ToString()\r\n    {\r\n        return $\"Pizza name: {Name}; Toppings: {string.Join(\", \", Toppings)}\";\r\n    }\r\n}<\/pre>\n<p>We expand our <code>Pizza<\/code> class by inheriting <code>ICloneable<\/code> and implementing the <code>Clone<\/code> method. This time we create our implementation where we return a new <code>Pizza<\/code> object and copy the parameters of the current instance &#8211; we assign <code>Name<\/code> directly as it is a <code>string<\/code> and then we use the <code>ToList<\/code> method we learned earlier to get a clone of the <code>Toppings<\/code> list.<\/p>\n<p>Then we get on with the cloning:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var pizzasClonedWithICloneable = new List&lt;Pizza&gt;();\r\n            \r\nforeach(var pizza in pizzas)\r\n{\r\n    pizzasClonedWithICloneable.Add((Pizza)pizza.Clone());\r\n}<\/pre>\n<p>To do this we create a <code>pizzasClonedWithICloneable<\/code> variable as an empty <code>List&lt;Pizza&gt;<\/code>. Then, in a <code>foreach<\/code> loop iterating over our initial <code>pizzas<\/code> list, we get a new copy of the current pizza using the <code>Clone<\/code> method and add it to our new list.<\/p>\n<h3><a id=\"UsingCopyConstructor\"><\/a>Clone a List Using a Copy Constructor<\/h3>\n<p>A copy constructor is a constructor that takes an instance of the type as a parameter. Then the values of each property of that object are copied over to the newly created instance of that type:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public Pizza(Pizza pizza)\r\n{\r\n    Name = pizza.Name;\r\n    Toppings = pizza.Toppings.ToList();\r\n}<\/pre>\n<p>In our <code>Pizza<\/code> class, we create a new constructor that takes in a <code>Pizza<\/code> as a parameter. In it, we assign the <code>Name<\/code> and <code>Toppings<\/code> properties the values of the passed-in object, keeping in mind that we need to pass a copy of the <code>Toppings<\/code>, done with <code>pizza.Toppings.ToList()<\/code>, and not just assign the value.<\/p>\n<p>Now, we can move back to our <code>Program<\/code> class and do the cloning:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var pizzasClonedWithCopyConstructor = new List&lt;Pizza&gt;();\r\n\r\nforeach (var pizza in pizzas)\r\n{\r\n    pizzasClonedWithCopyConstructor.Add(new Pizza(pizza));\r\n}<\/pre>\n<p>Similar to the <code>ICloneable<\/code> example, we create a new <code>pizzasClonedWithCopyConstructor<\/code> variable and initialize it with an empty <code>List&lt;Pizza&gt;<\/code>. Once this is done we create a <code>foreach<\/code> loop and on each iteration we use the copy constructor, <code>new Pizza(pizza)<\/code>, to add a copy of the current <code>pizza<\/code> to our new list.<\/p>\n<p>Now, that we have used our two methods of creating a deep copy, let&#8217;s test them:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var margherita = pizzas\r\n    .FirstOrDefault(x =&gt; x.Name == \"Margherita\");\r\n\r\nmargherita.Toppings.Clear();\r\n\r\nConsole.WriteLine($\"Original Margherita: {pizzas.First()}\");\r\nConsole.WriteLine($\"Cloned with ICloneable: {pizzasClonedWithICloneable.First()}\");\r\nConsole.WriteLine($\"Cloned with Copy Constructor: {pizzasClonedWithCopyConstructor.First()}\");<\/pre>\n<p>After the last <code>foreach<\/code> loop in our <code>Program<\/code> class, we again get the Margherita pizza and clear its list of <code>Toppings<\/code>. Then we print our Margherita pizzas on the console and examine the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Original Margherita: Pizza name: Margherita; Toppings:\r\nCloned with ICloneable: Pizza name: Margherita; Toppings: Mozzarella, Olive oil, Basil\r\nCloned with Copy Constructor: Pizza name: Margherita; Toppings: Mozzarella, Olive oil, Basil<\/pre>\n<p>This time around we can see that our task to create a deep copy when trying to clone a List was successful and the cloned pizzas have their <code>Toppings<\/code> intact as we have indeed created a deep copy with both approaches.<\/p>\n<h2><a id=\"Conclusion\"><\/a>Conclusion<\/h2>\n<p>In this article, we learned all about how to clone a List in C#. We also learned that shallow copies are easy to achieve in many ways and work wonders with value types but may cause headaches when used with reference types. Deep copies are very useful but tend to be more expensive than shallow ones, due to the need for additional object creation. It can also be very complicated to achieve if we deal with very complex objects. The good thing is that now you are prepared to tackle the cloning of <code>List&lt;T&gt;<\/code>, no matter if the <code>T<\/code> is a value or a reference type.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will look at all the different ways we can clone a List in C# to another and what we should pay attention to when doing so. In C# we have ample ways of doing that, so let&#8217;s dive right in. How to Clone a List in C# That Contains Value Types [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12,1381],"tags":[570,1617,380,1619,1615,376,1618,1616],"class_list":["post-81588","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","category-list","tag-addrange","tag-convertall","tag-copyto","tag-deep-copy","tag-how-to-clone-a-list","tag-list","tag-shalow-copy","tag-tolist","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Clone a List in C#? - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Clone a List in C#? - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-08T07:34:27+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-02-09T08:13:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Clone a List in C#?\",\"datePublished\":\"2023-02-08T07:34:27+00:00\",\"dateModified\":\"2023-02-09T08:13:06+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\"},\"wordCount\":1642,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"AddRange\",\"ConvertAll\",\"CopyTo\",\"Deep Copy\",\"How to clone a list\",\"list\",\"Shalow copy\",\"ToList\"],\"articleSection\":[\"C#\",\"List\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\",\"url\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\",\"name\":\"How to Clone a List in C#? - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-02-08T07:34:27+00:00\",\"dateModified\":\"2023-02-09T08:13:06+00:00\",\"description\":\"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Clone a List in C#?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Clone a List in C#? - Code Maze","description":"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/","og_locale":"en_US","og_type":"article","og_title":"How to Clone a List in C#? - Code Maze","og_description":"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.","og_url":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/","og_site_name":"Code Maze","article_published_time":"2023-02-08T07:34:27+00:00","article_modified_time":"2023-02-09T08:13:06+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Clone a List in C#?","datePublished":"2023-02-08T07:34:27+00:00","dateModified":"2023-02-09T08:13:06+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/"},"wordCount":1642,"commentCount":2,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["AddRange","ConvertAll","CopyTo","Deep Copy","How to clone a list","list","Shalow copy","ToList"],"articleSection":["C#","List"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/","url":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/","name":"How to Clone a List in C#? - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-02-08T07:34:27+00:00","dateModified":"2023-02-09T08:13:06+00:00","description":"In this article, we will look at all the different ways we can clone a list in C# and what we should pay attention to when doing so.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-how-to-clone-a-list\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Clone a List in C#?"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/81588","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=81588"}],"version-history":[{"count":6,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/81588\/revisions"}],"predecessor-version":[{"id":81668,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/81588\/revisions\/81668"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=81588"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=81588"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=81588"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}