How do I change my new list without changing the original list?

后端 未结 11 1867
萌比男神i
萌比男神i 2020-12-03 08:30

I have a list that gets filled in with some data from an operation and I am storing it in the memory cache. Now I want another list which contains some sub data from the li

相关标签:
11条回答
  • 2020-12-03 09:06

    Your are seeing the original list being modified because, by default, any non-primitive objects, are passed by reference (It is actually pass by value, the value being the reference, but that is a different matter).

    What you need to do is clone the object. This question will help you with some code to clone a List in C#: How do I clone a generic list in C#?

    0 讨论(0)
  • 2020-12-03 09:10

    I tried many of the answers above. On all the ones I tested, an update to the new list modifies the original. this is what works for me.

    var newList = JsonConvert.DeserializeObject<List<object>>(JsonConvert.SerializeObject(originalList));
    return newlist.RemoveAt(3);
    
    0 讨论(0)
  • 2020-12-03 09:13

    Even if you create a new list, the references to the items in the new list will still point to the items in the old list, so I like to use this extension method if I need a new list with new references...

    public static IEnumerable<T> Clone<T>(this IEnumerable<T> target) where T : ICloneable
    {
        If (target.IsNull())
            throw new ArgumentException();
    
        List<T> retVal = new List<T>();
    
        foreach (T currentItem in target)
            retVal.Add((T)(currentItem.Clone()));
    
        return retVal.AsEnumerable();
    }
    
    0 讨论(0)
  • 2020-12-03 09:13

    Your target variable is a reference type. This means that anything you do to it will be reflected in the list you pass into it.

    To not do that, you are going to need to create a new list in the method, copy target contents to it, and then perform the remove at operation on the new list.

    About Reference and Value Types

    0 讨论(0)
  • 2020-12-03 09:16

    Just make sure that you initialize the new list with a list created by copying the elements of the source list.

    List<Item> target = mainList; Should be List<item> target = new List<Item>(mainList);

    0 讨论(0)
提交回复
热议问题