0

i have a list of class of below type

public class Class1
{
    public string str1 { get; set; }
    public string str2 { get; set; }
    public int int1 { get; set; }
    public double dbl1{get;set;}
    public List<Class2> cls2 { get; set; }
    public List<string> str3 { get; set; }

}

in which Class 2 is also a user defined class like:

public class Class2
{
    public string str4{ get; set; }
    public Class3 cls2 { get; set; }
}

which Class3 is also another user defined class. I need to copy a List<Class1> to another list of this type without any reference to the first list.

I used the below ways but they were unsuccessful.

  1. .CopyTo() to an Class1[] array and then .ToList() but this hold the references
  2. .ToList() but this hold the references
  3. I used the ways of serializable and deserializable but the class could not be serializable.
jltrem
  • 12,124
  • 4
  • 40
  • 50
virii
  • 73
  • 1
  • 10
  • You will just have to write a Method. Optionally implementing the IClonable interface. – H H Aug 25 '15 at 12:54
  • Are you happy to write a `DeepClone()` method (or implement a Copy Constructor) for each class? (I'd avoid implementing `ICloneable` because it doesn't specify whether it's deep or shallow - and [Microsoft recommend that it not be used](https://msdn.microsoft.com/en-us/library/system.icloneable%28v=vs.110%29.aspx).) – Matthew Watson Aug 25 '15 at 12:54

2 Answers2

0

You should use write a generic method that uses serialization, that way you can easily achieve deep cloning to complex objects with good maintainability.

Refer to this: How do you do a deep copy of an object in .NET (C# specifically)?

Community
  • 1
  • 1
Felix Av
  • 1,254
  • 1
  • 14
  • 22
  • i use serializable but it does not work and cant serialize the list. – virii Aug 25 '15 at 13:04
  • then add your code that does that, please, so we can have a look – Felix Av Aug 25 '15 at 13:07
  • ' public object DeepClone(object obj) { object objResult = null; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf=new BinaryFormatter(); bf.Serialize(ms,obj); ms.Position = 0; objResult = bf.Deserialize(ms); } return objResult; }' – virii Aug 25 '15 at 13:22
  • Whats the error you get? Is your class decorated with [Serializable] attribute? – Felix Av Aug 25 '15 at 13:26
  • first i am very thank you for your time and help. error make in bf.Serialize(ms,obj). – virii Aug 25 '15 at 13:29
  • no problem. I think it's because your class didn't have [Serializable] attribute on your class. If it was helpful, please mark the question as answered and feel free to upvote the answer ;-) – Felix Av Aug 25 '15 at 13:33
0

I use serialization and deserialization method from NewtonSoft.Json package and it worked well.

virii
  • 73
  • 1
  • 10