How do I clone a generic list in C#?

前端 未结 26 2487
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  爱一瞬间的悲伤
    2020-11-22 02:13

    Unless you need an actual clone of every single object inside your List, the best way to clone a list is to create a new list with the old list as the collection parameter.

    List myList = ...;
    List cloneOfMyList = new List(myList);
    

    Changes to myList such as insert or remove will not affect cloneOfMyList and vice versa.

    The actual objects the two Lists contain are still the same however.

提交回复
热议问题