Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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)) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata