List<int> oldList = new List<int>( ); List<int> newList = new List<int>( ); newList.AddRange(oldList);
Shadow Copy Use Map
1 2 3 4 5 6 7 8
var List1= new List<Entities1>(); var List2= new List<Entities2>(); var List2 = List1.Select(p => new Entities2 { EntityCode = p.EntityCode, EntityId = p.EntityId, EntityName = p.EntityName }).ToList();
…
2. Deep Copy
DeepCopy with BinaryFormatter
Your object requires to be [Serializable()]. The goal is to lose all references and build new ones.
1 2 3 4 5 6 7 8 9 10 11 12 13
publicstaticobjectDeepClone(object obj) { object objResult = null; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, obj);
DeepCopy implement ICloneable or use copy-constructor
this is a very good method!
If your elements are value types
1
List<YourType> newList = new List<YourType>(oldList);
However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this:
1 2 3 4 5 6 7
List<ICloneable> oldList = new List<ICloneable>(); List<ICloneable> newList = new List<ICloneable>(oldList.Count);
Personally, I would avoid ICloneable because of the need to guarantee a deep copy of all members. Instead, I’d suggest the copy-constructor or a factory method like YourType.CopyFrom(YourType itemToCopy) that returns a new instance of YourType.
publicstaticclassListEx { //This method will create a copy of your list but your type should be serializable. publicstaticList<T> CopyList<T>(this List<T> lst) { List<T> lstCopy = new List<T>(); foreach (var item in lst) { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, item); stream.Position = 0; lstCopy.Add((T)formatter.Deserialize(stream)); } } return lstCopy; } } }