
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
314
|
Chapter 5: Collections
5.13 Storing Snapshots of Lists in an Array
Problem
You have an ArrayList, Queue,orStack object and you want to take a snapshot of its
current state. (Note that this recipe also works for any other data type that imple-
ments the
ICollection interface.)
Solution
Use the CopyTo method declared in the ICollection interface. The following method,
TakeSnapshotOfList, accepts any type that implements the ICollection interface and
takes a snapshot of the entire object’s contents. This snapshot is returned as an
object array:
public static T[] TakeSnapshotOfList<T>(ICollection theList)
{
T[] snapshot = new T[theList.Count];
theList.CopyTo(snapshot, 0);
return (snapshot);
}
Discussion
The following method creates a Queue<int> object, enqueues some data, and then
takes a snapshot of it:
public static void TestListSnapshot( )
{
Queue<int> someQueue = new Queue<int>( );
someQueue.Enqueue(1);
someQueue.Enqueue(2);
someQueue.Enqueue(3);
int[] queueSnapshot = TakeSnapshotOfList<int>(someQueue);
}
The TakeSnapshotOfList<T> is useful when you want to record the state of an object
that implements the
ICollection interface. This “snapshot” can be compared to the
original list later on to determine what, if anything, has changed in the list. Multiple
snapshots can be taken at various ...