What is the best way to copy a BindingList?
Just use ForEach()? Or are there better ways?
What is the best way to copy a BindingList?
Just use ForEach()? Or are there better ways?
BindingList has a constructor which can take an IList. And BindingList implements IList. So you can just do the following:
BindingList newBL = new BindingList(oldBL);
Of course that creates a second list that just points at the same objects. If you actually want to clone the objects in the list then you have to do more work.
Foreach pretty much is the easiest way, and the performance overhead is minimal if any.
From a deleted answer:
Serialize the object then de-serialize to get a deep cloned non referenced copy
Which is a valid option if the OP wants a deep copy.
We use the Serialize / De-serialize route to get a deep copy of the list. It works well but it does slow performance down in larger lists, such as for search screens, so I'd avoid using it on lists with 5000+ items.
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ProjectName.LibraryName.Namespace { internal static class ObjectCloner { /// /// Clones an object by using the . /// /// The object to clone. /// /// The object to be cloned must be serializable. /// public static object Clone(object obj) { using (MemoryStream buffer = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(buffer, obj); buffer.Position = 0; object temp = formatter.Deserialize(buffer); return temp; } } } }
© 2022 - 2024 — McMap. All rights reserved.