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

后端 未结 11 1895
萌比男神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 08:50

    Build a new list first and operate on that, because List is a reference type, i.e. when you pass it in a function, you do not just pass the value but the actual object itself.

    If you just assign target to mainList, both variables point to the same object, so you need to create a new List:

    List target = new List(mainList);
    

    void List SomeOperationFunction() makes no sense, because either you return nothing (void) or you return a List. So either remove the return statement from your method or return a new List. In the latter case, I would rewrite this as:

    List target = SomeOperationFunction(mainList);
    
    List SomeOperationFunction(List target)
    {
        var newList = new List(target);
        newList.RemoveAt(3);
        return newList;
    }
    

提交回复
热议问题