
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Inserting and Removing Items from an Array
|
301
{
Console.WriteLine("obj5: " + o);
}
}
}
This code outputs the following:
--GET All--
obj2: 2
obj2: 2
obj2: 2
obj2: 2
obj5: 5
--BINARY SEARCH GET ALL--
obj2: 2
obj2: 2
obj2: 2
obj2: 2
obj5: 5
The BinarySearchGetAll method is faster than the GetAll method, especially if the
array has already been sorted. If a
BinarySearch is used on an unsorted List<T>,itis
highly likely that the results returned by the search will be incorrect.
See Also
See Recipe 5.6; see the “List<T> Class” topic in the MSDN documentation.
5.8 Inserting and Removing Items from an Array
Problem
You need the ability to insert and remove items from a standard System.Array type.
When an item is inserted, it should not overwrite the item where it is being inserted;
instead, it should be inserted between the element at that index and the previous
index. When an item is removed, the void left by the element should be closed by
shifting the other elements in the array. However, the
Array type has no usable
method to perform these operations.
Solution
If possible, switch to a List<T> instead. If this is not possible (for example, if you’re
not in control of the code that creates the
Array or ArrayList in the first place), use
the approach shown in the following class. Two methods insert and remove ...