1. When T in the list <t> object is of the value type (INT type, etc)
ForValue TypeYou can copy the list directly using the following method:
List<T> oldList = new List<T>(); oldList.Add(..); List<T> newList = new List<T>(oldList);
Ii. When T in the list <t> object is of the reference type (for example, a custom object class)
1. You cannot copy a list of reference types using the above method. Instead, the list will only copy the reference of objects in the list. You can use the following extension method to copy the list:
Static class extensions {public static ilist <t> clone <t> (this ilist <t> listtoclone) where T: icloneable {return listtoclone. select (item => (t) item. clone ()). tolist ();} // Of course, the previous question is that the object in the list must implement the icloneable interface}
2. Another method is to perform deep copy on the referenced object in serialization mode. This method is the most reliable.
Public static t clone <t> (T realobject) {using (Stream objectstream = new memorystream () {// use system. runtime. serialization and deserialization complete the copying of the referenced object iformatter formatter = new binaryformatter (); formatter. serialize (objectstream, realobject); objectstream. seek (0, seekorigin. begin); Return (t) formatter. deserialize (objectstream );}}
3. Use System. xml. serialization to implement serialization and deserialization
public static T Clone<T>(T RealObject) { using(Stream stream=new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stream, RealObject); stream.Seek(0, SeekOrigin.Begin); return (T)serializer.Deserialize(stream); }}
Iii. Test the deep copy of the above objects
The test is as follows: using system; using system. collections. generic; using system. collections; using system. LINQ; using system. text; using system. io; using system. runtime. serialization; using system. runtime. serialization. formatters. binary; namespace LINQ {[serializable] public class TT {private string name = ""; Public string name {get {return name ;}set {name = value ;}} private string sex = ""; Public String sex {get {return sex;} set {sex = value ;}}} class linqtest {public static t clone <t> (T realobject) {using (Stream objectstream = new memorystream () {iformatter formatter = new binaryformatter (); formatter. serialize (objectstream, realobject); objectstream. seek (0, seekorigin. begin); Return (t) formatter. deserialize (objectstream) ;}} public static void main () {list <tt> lsttt = new list <tt> (); TT TT1 = new TT (); tt1.name = "A1"; tt1.sex = "20"; lsttt. add (TT1); List <tt> l333 = new list <tt> (); l333.add (clone <tt> (lsttt [0]); l333 [0]. name = "333333333 ";}}}