Hello, friends,
I need to make a copy of a collection of user defined class, which
contains
DataTable and other data type properties.
However, I don't want to iterate each item. Any better way?
It depends on what collection class you're using. But, for example, if
it's a class that can be instantiated using an array of the original
objects, and it implements ICollection/ICollection<T> (and why wouldn't
it?
), you could use the ICollection.ToArray() method to get an array,
and then use that array to create a new instance of the collection.
This has the disadvantage that you wind up copying the data in the
collection twice. But it's easy to write, and as long as copying the list
isn't a performance bottleneck, I wouldn't worry about the double copy.
Alternatively, if you're using .NET 3.5, LINQ offers the ToList()
extension method. If your collection is actually a List<T>, then that'd
be a direct method of creating a new copy of the List<T> straight from the
original. It seems to me that the method exists mainly to support LINQ's
database access features, but if you can use it, why not?
Note of course that even using these techniques, _some_ code has to
iterate each item. You may be able to avoid writing the code explicitly
to do so, depending on the circumstance, but you can't avoid having the
code actually do it. This is probably obvious, but I figure I should
mention it anyway.
Pete