9.7. Retrieving All Instances of a Specific Itemin an ArrayList

Problem

You need to retrieve every object that matches a search criteria contained in an ArrayList. The ArrayList contains the BinarySearch method to find a single item—essentially, there is no find all functionality. If you want to find all items duplicated in an ArrayList, you must write your own routine.

Solution

The following class inherits from the ArrayList class in order to extend its functionality. Two methods are added to return an array of all the matching objects found in this sorted or unsorted ArrayList:

using System; using System.Collections; public class ArrayListEx : ArrayList { // The method to retrieve all matching objects in a // sorted or unsorted ArrayListEx public object[] GetAll(object searchValue) { ArrayList foundItem = new ArrayList( ); for (int index = 0; index < this.Count; index++) { if (this[index].Equals(searchValue)) { foundItem.Add(this[index]); } } return (foundItem.ToArray( )); } // The method to retrieve all matching objects in a sorted ArrayListEx public object[] BinarySearchAll(object searchValue) { // Sort ArrayList this.Sort( ); bool done = false; ArrayList RetObjs = new ArrayList( ); // Search for first item int center = this.BinarySearch(searchValue); int left = center - 1; int right = center + 1; int position = -1; if (center >= 0) { // Add first found RetObjs.Add(this[center]); // Search to the left do { if (left < 0) { done = true; } else { if (this[left].Equals(searchValue)) ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.