Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method to create deep copy of all elements in a collection

Tags:

c#

generics

I have various ObservableCollections of different object types. I'd like to write a single method that will take a collection of any of these object types and return a new collection where each element is a deep copy of elements in the given collection. Here is an example for a specifc class

   private static ObservableCollection<PropertyValueRow> DeepCopy(ObservableCollection<PropertyValueRow> list)
   {
        ObservableCollection<PropertyValueRow> newList = new ObservableCollection<PropertyValueRow>();
        foreach (PropertyValueRow rec in list)
        {
            newList.Add((PropertyValueRow)rec.Clone());
        }
        return newList;
   }

How can I make this method generic for any class which implements ICloneable?

like image 452
bwarner Avatar asked Apr 30 '10 13:04

bwarner


People also ask

How do I clone a generic list in C#?

To clone a list just call . ToList(). This creates a shallow copy.

What is deep cloning in Java?

2. Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.

What is shallow copy and deep copy in C#?

A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.


2 Answers

You could do something like this:

private static ObservableCollection<T> DeepCopy<T>(ObservableCollection<T> list)
    where T : ICloneable
{
   ObservableCollection<T> newList = new ObservableCollection<T>();
   foreach (T rec in list)
   {
       newList.Add((T)rec.Clone());
   }
   return newList;
}

Note that you could make this more general by taking IEnumerable<T>, and LINQ makes it even easier:

private static ObservableCollection<T> DeepCopy<T>(IEnumerable<T> list)
    where T : ICloneable
{
   return new ObservableCollection<T>(list.Select(x => x.Clone()).Cast<T>());
}
like image 190
Jon Skeet Avatar answered Oct 21 '22 17:10

Jon Skeet


private static ObservableCollection<T> DeepCopy<T>(ObservableCollection<T> list) 
    where T : ICloneable 
{ 
   ObservableCollection<T> newList = new ObservableCollection<T>(); 
   foreach (T rec in list) 
   { 
       newList.Add((T)rec.Clone()); 
   } 
   return newList; 
} 
like image 43
Hinek Avatar answered Oct 21 '22 15:10

Hinek