code_junkie

How do I clone a generic list in C#?

Nov 11th, 2011
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. static class Extensions
  2. {
  3. public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
  4. {
  5. return listToClone.Select(item => (T)item.Clone()).ToList();
  6. }
  7. }
  8.  
  9. List<YourType> newList = new List<YourType>(oldList);
  10.  
  11. List<ICloneable> oldList = new List<ICloneable>();
  12. List<ICloneable> newList = new List<ICloneable>(oldList.Count);
  13.  
  14. oldList.ForEach((item) =>
  15. {
  16. newList.Add((ICloneable)item.Clone());
  17. });
  18.  
  19. List<YourType> oldList = new List<YourType>();
  20. List<YourType> newList = new List<YourType>(oldList.Count);
  21.  
  22. oldList.ForEach((item)=>
  23. {
  24. newList.Add(new YourType(item));
  25. });
  26.  
  27. public static object DeepClone(object obj)
  28. {
  29. object objResult = null;
  30. using (MemoryStream ms = new MemoryStream())
  31. {
  32. BinaryFormatter bf = new BinaryFormatter();
  33. bf.Serialize(ms, obj);
  34.  
  35. ms.Position = 0;
  36. objResult = bf.Deserialize(ms);
  37. }
  38. return objResult;
  39. }
  40.  
  41. List<int> oldList = new List<int>( );
  42. // Populate oldList...
  43.  
  44. List<int> newList = oldList.GetRange(0, oldList.Count);
  45.  
  46. List<int> newList = new List<int>(oldList);
  47.  
  48. List<T> Clone<T>(IEnumerable<T> oldList)
  49. {
  50. return newList = new List<T>(oldList);
  51. }
  52.  
  53. List<string> myNewList = Close(myOldList);
  54.  
  55. public static Object CloneType(Object objtype)
  56. {
  57. Object lstfinal = new Object();
  58.  
  59. using (MemoryStream memStream = new MemoryStream())
  60. {
  61. BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
  62. binaryFormatter.Serialize(memStream, objtype); memStream.Seek(0, SeekOrigin.Begin);
  63. lstfinal = binaryFormatter.Deserialize(memStream);
  64. }
  65.  
  66. return lstfinal;
  67. }
  68.  
  69. public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
  70. {
  71. public object Clone()
  72. {
  73. var clone = new List<T>();
  74. ForEach(item => clone.Add((T)item.Clone()));
  75. return clone;
  76. }
  77. }
  78.  
  79. public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
  80. {
  81. public object Clone()
  82. {
  83. var clone = new List<T>();
  84. ForEach(item => clone.Add((T)item.Clone()));
  85. return clone;
  86. }
  87. }
Add Comment
Please, Sign In to add comment