How do I clone a generic list in C#?

前端 未结 26 2997
失恋的感觉
失恋的感觉 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:10

    If you have already referenced Newtonsoft.Json in your project and your objects are serializeable you could always use:

    List newList = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(listToCopy))
    

    Possibly not the most efficient way to do it, but unless you're doing it 100s of 1000s of times you may not even notice the speed difference.

提交回复
热议问题