
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
298
|
Chapter 5: Collections
find the very last matching item, and the position of this element is recorded in the
right variable. The value in the left variable is subtracted from the value in the
right variable and then one is added to this result in order to get the total number of
matches.
Recipe 5.7 contains a variation of this recipe that returns the actual items found,
rather than a count.
See Also
See Recipe 5.7; see the “ArrayList Class” topic in the MSDN documentation.
5.7 Retrieving All Instances of a Specific Item
in a List<T>
Problem
You need to retrieve every object contained in a List<T> that matches a search crite-
rion. The
List<T> contains the BinarySearch method to find a single item—essen-
tially, there is no find all functionality. If you want to find all items duplicated in a
List<T>, you must write your own routine.
Solution
Use the ListEx<T> class shown in Example 5-3, which inherits from the List<T> class in
order to extend its functionality. Two methods—
GetAll and BinarySearchGetAll—are
added to return an array of all the matching objects found in this sorted or unsorted
List<T>.
Example 5-3. Retrieving all instances of a specific item in a List<T>
using System;
using System.Collections;
using System.Collections.Generic;
public class ListEx<T> : List<T>
{
// The method to ...