Efficiently Duplicating Generic Lists in C#
Creating a copy of a generic list is a frequent task in C#, though the language lacks a direct list.Clone()
method. This article explores several effective strategies for duplicating lists.
Value Type List Duplication:
For lists containing value types, copying is simple:
<code class="language-csharp">List<YourType> newList = new List<YourType>(oldList);</code>
This creates a new list with identical elements to the original. Note that this performs a shallow copy for value types.
Deep Copying Reference Type Lists:
With reference types, a deep copy is necessary to avoid shared object references. If your elements implement ICloneable
:
<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>
This iterates and clones each element individually.
Leveraging Copy Constructors:
If your elements have copy constructors but don't implement ICloneable
:
<code class="language-csharp">List<YourType> oldList = new List<YourType>(); List<YourType> newList = new List<YourType>(oldList.Count); oldList.ForEach(item => newList.Add(new YourType(item)));</code>
This utilizes the copy constructor for each element.
Custom Cloning Methods:
For more complex scenarios, consider a custom copy method (e.g., YourType.CopyFrom()
) or a factory method to provide fine-grained control over the cloning process.
Encapsulation for Reusability:
For improved code organization and reusability, wrap these approaches into extension methods or standalone helper functions.
The above is the detailed content of How to Efficiently Duplicate a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!