问题
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