| Description |
The CopyTo method takes all elements from the current SortedList and overlays these values onto elements of the TargetArray.
The overlay starts at the TargetIndex value.
Important : the TargetArray must be created in advance - the CopyTo method overlays - it does not build. Also, the target array must have at least the same capacity as the number of elements being overlaid (copied).
Important : the TargetArray data type must be able to accomodate the DictionaryEntry type in the copy process. If the CopyTo method cannot cast to the target array, then an exception is thrown.
Just like Clone, CopyTo performs a shallow copy. When the current SortedList holds reference (non primitive) data types, the target array element values still refer to the same objects that current array elements refer to. This is what is referred to as a shallow copy. A deep copy would create new versions of the referred objects.
|
|
| Microsoft MSDN Links |
System.Collections
System.Collections.SortedList
|
|
|
| Copying the whole SortedList onto the middle of an Array |
program Project1;
{$APPTYPE CONSOLE}
uses
System.Collections;
var
MyList : System.Collections.SortedList;
MyArray : System.Array;
DictEntry : DictionaryEntry;
i : Integer;
begin
// Create our sorted list
MyList := SortedList.Create;
// And fill it
MyList['Age'] := TObject(47);
MyList['Birthday'] := DateTime.Create(1957, 2, 18);
MyList['Name'] := 'Neil Moffatt';
// Create the target array
MyArray := System.Array.CreateInstance(TypeOf(TObject), 9);
// And fill it
MyArray.SetValue('0.', 0);
MyArray.SetValue('1.', 1);
MyArray.SetValue('2.', 2);
MyArray.SetValue('3.', 3);
MyArray.SetValue('4.', 4);
MyArray.SetValue('5.', 5);
MyArray.SetValue('6.', 6);
MyArray.SetValue('7.', 7);
MyArray.SetValue('8.', 8);
// Copy to the array
Console.WriteLine('Copying from SortedList to the array :');
Console.WriteLine;
MyList.CopyTo(MyArray, 3);
// Display the array contents
for i := 0 to MyArray.Length-1 do
begin
if MyArray.GetValue(i).GetType = TypeOf(String)
then Console.WriteLine('String : {0}',
MyArray.GetValue(i).ToString);
if MyArray.GetValue(i).GetType = TypeOf(DictionaryEntry)
then
begin
DictEntry := DictionaryEntry(MyArray.GetValue(i));
Console.WriteLine('Dictionary entry : {0} = {1}',
DictEntry.Key.ToString,
DictEntry.Value.ToString);
end;
end;
Console.Readline;
end.
| | Show full unit code | Copying from SortedList to the array :
String : 0.
String : 1.
String : 2.
Dictionary entry : Age = 47
Dictionary entry : Birthday = 18/02/1957 00:00:00
Dictionary entry : Name = Neil Moffatt
String : 6.
String : 7.
String : 8.
|
| |
|
|
|