Can you create deep copy of nested lists through use of it's constructor?

倖福魔咒の 提交于 2019-12-11 03:34:34

问题


I know you can give a list object as parameter of list constructor to copy 1 list to the other.

By doing so, you can create a deep copy if used types are simple build-in once (which precisely?). For example of type string:

List<string> testList = new List<string>();

List<string> testListCopy = new List<string>(testList );

Can you create a deep copy if you work with nested Lists? :

List<List<string>> testList = new List<List<string>>();

List<List<string>> testListCopy = new List<List<string>>(testList );

回答1:


The List<T> constructor won't do this for you, but you can do it yourself with:

List<List<string>> testList = new List<List<string>>();
List<List<string>> testListCopy = new List<List<string>>(testList.Select(x => x.ToList()));

Or even this, which is equivalent:

List<List<string>> testListCopy = testList.Select(x => x.ToList()).ToList();



回答2:


A copy is not just shallow or deep. It's a scale with multiple values along it with a "most deep" and "most shallow" option. Just using a list's copy constructor results in a copy that's somewhere in the middle; it is not a "deep copy".

What you're doing is re-creating a new list, without copying a reference to it, but you're performing a shallow copy on the items in that list. If the items in that inner list are themselves lists, or other mutable reference types, you'd need to do a deep copy of them, and of all of their referenced fields, etc. all the way down the chain. That would be a truly "deep" copy. Doing so is non-trivial, and impossible in the general case. There is no truly effective way to write an implementation for public static T DeepCopy<T>(T object) that would work for any type. (You can get close by trying to leverage serialization, but not all objects can be serialized).

As to the specific case of a List<List<string>>, you simply need to create a new outer list, as well as new lists for each of the inner lists. P.s.w.g has given a good answer to this particular problem:

List<List<string>> listCopy = list.Select(x => x.ToList()).ToList();


来源:https://stackoverflow.com/questions/16068688/can-you-create-deep-copy-of-nested-lists-through-use-of-its-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!