This guide explores different methods for duplicating generic lists in C#. Since List<T>
doesn't have a built-in Clone()
method, we'll examine several strategies.
Shallow Copy for Value Types
For lists containing value types (like int
, double
), a simple shallow copy is sufficient:
<code class="language-csharp">List<YourType> newList = new List<YourType>(oldList);</code>
Deep Copy for Reference Types: Using ICloneable
If your list holds reference types and you require a deep copy (a completely independent copy of the data), and those types implement the ICloneable
interface, you can use this approach:
<code class="language-csharp">List<ICloneable> oldList = new List<ICloneable>(); List<ICloneable> newList = new List<ICloneable>(oldList.Count); oldList.ForEach(item => { newList.Add((ICloneable)item.Clone()); });</code>
Deep Copy for Reference Types: Leveraging Copy Constructors
If your element type has a copy constructor but doesn't implement ICloneable
, this method is preferable:
<code class="language-csharp">List<YourType> oldList = new List<YourType>(); List<YourType> newList = new List<YourType>(oldList.Capacity); // Use Capacity for efficiency oldList.ForEach(item => { newList.Add(new YourType(item)); });</code>
Best Practice: Factory Methods or Copy Constructors
For robust deep copying, it's highly recommended to utilize a factory method (e.g., YourType.CopyFrom()
) or a copy constructor within your custom class. This provides greater control and ensures a complete deep copy of all member variables.
Encapsulating the Logic
For improved code organization and reusability, consider wrapping any of these techniques into an extension method or a dedicated helper function.
The above is the detailed content of How to Clone a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!