1

I need to know how to deep clone a List <Business> object. I tried the following:

List< Business> owner = bus.Select(m => new Business{
    Businessname= m.Businessname,
    Locations= m.Locations,

 }).ToList();

I removed an object (Locations - Locations is a List <Country>) from owner object. I expected no changes in the bus object as I cloned it as shown in the above code.

However, the object Locations has also got deleted from the bus object. Can someone tell me how to fix this ?

Siavash
  • 2,813
  • 4
  • 29
  • 42
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • 1
    `Locations= m.Locations,`, that's not in any way a clone, that's only a reference assignment. If you want to clone, you will need to do something like `m.Locations.Select(l => new Country { ... }).ToList()` – Camilo Terevinto Oct 21 '18 at 13:00
  • I am getting an error. In the `owner ` object there are also some `Locations` which are `null`. So, when it tries to clone the `Country` it hits an error. How could I prevent this from happening ? Help – Sharon Watinsan Oct 21 '18 at 13:18
  • 2
    @SiavashGhanbari Did you read the content of what you shared above. It's in Python and not C#. – Sharon Watinsan Oct 21 '18 at 13:25
  • that's my fault, I deleted the flag and comment @sharonHwk – Siavash Oct 21 '18 at 13:26
  • Any help on this ? – Sharon Watinsan Oct 21 '18 at 13:31
  • Possible duplicate of [How to deep copy a list?](https://stackoverflow.com/questions/17873384/how-to-deep-copy-a-list) – T.S. Oct 21 '18 at 19:38

2 Answers2

0

You should perform your clone operation as follows:

List< Business> owner = bus.Select(m => new Business
{
    Businessname = m.Businessname,
    Locations = m.Locations?.Select(l => new Country { /*here goes your initialization*/})
})
.ToList();

The operator ? does null check and if Locations field is null it stops execution and returns null, otherwise it performs Select operation.

Please, note that if Country object also contains reference typed fields, you should explicitly create that objects and copy all the fields.

NamiraJV
  • 658
  • 1
  • 7
  • 11
0

The easiest and most universal way of deep-cloning pretty much any object or data structure is to serialize and de-serialize it back. Newtonsoft JSON is pretty fast and smart enough to handle complex scenarios such as circular references, interface-typed fields and more.

var str = JsonConvert.SerializeObject(myList);
var deepCopy = JsonConvert.DeserializeObject<List<MyObject>>(str);

However, this is probably not the fastest way, since it does a lot of extra work and allocations.

Impworks
  • 2,647
  • 3
  • 25
  • 53