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

后端 未结 11 1884
萌比男神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:54

    You need to clone your list in your method, because List is a class, so it's reference-type and is passed by reference.

    For example:

    List SomeOperationFunction(List target)
    {
      List tmp = target.ToList();
      tmp.RemoveAt(3);
      return tmp;
    }
    

    Or

    List SomeOperationFunction(List target)
    {
      List tmp = new List(target);
      tmp.RemoveAt(3);
      return tmp;
    }
    

    or

    List SomeOperationFunction(List target)
    {
      List tmp = new List();
      tmp.AddRange(target);
      tmp.RemoveAt(3);
      return tmp;
    }
    

提交回复
热议问题