Clone a List in PCL

Hi,

so what is the best way to clone a List? If I clone List A to B and change something in A, I don't want this changes in List B.
Right now I clone my list like this:
public class ModelClass{ public int Id { get; set; } public string Title { get; set; } = string.Empty; public ModelClass Clone() { return (ModelClass)this.MemberwiseClone(); } }
The other class:
... foreach (var item in ListA) { ListB.Add(item.Clone()); } ...

Tagged:

Posts

  • kentuckerkentucker USMember ✭✭✭✭✭

    There are a bunch of ways you can do. Create a new List and loop through the values in the old list. Create a new instance of the class and set its properties to the same value as the property in the old class. I guess you could also serialize the list to json with json.net and deserialize into a new class with json.net

  • kentuckerkentucker USMember ✭✭✭✭✭
    edited March 2017

    Here is an example that uses Json.Net

        public T CloneObject<T>(T toBeCloned)
        {
            T clone = default(T);
            string serialized = JsonConvert.SerializeObject(toBeCloned);
            clone = JsonConvert.DeserializeObject<T>(serialized);
            return clone;
        }
    
  • MartinWunderlichMartinWunderlich USMember ✭✭

    Good idea. Do you think the JSON-Method is faster than mine?
    I think to create a new List and loop through the values in the old list wouldn't be fast.
    Especially, when you use for-loop...

  • kentuckerkentucker USMember ✭✭✭✭✭

    I am not sure which method is faster. You would have to do some tests with large datasets to see which method is faster. I prefer it because I do not have to add the clone method to my classes

Sign In or Register to comment.