O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required