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.6. Determining the Number of Times an Item Appears in an ArrayList

Problem

You need the number of occurrences of one type of object contained in an ArrayList. The ArrayList contains methods, such as Contains and BinarySearch to find a single item. Unfortunately, these methods cannot find all duplicated items at one time—essentially, there is no count all functionality. If you want to find multiple items, you need to implement your own routine.

Solution

The following class inherits from the ArrayList class in order to extend its functionality. Two methods are added to return the number of times a particular object appears in a sorted and an unsorted ArrayList:

using System; using System.Collections; public class ArrayListEx : ArrayList { // Count the number of times an item appears in this // unsorted or sorted ArrayList public int CountAll(object searchValue) { int foundCounter = 0; for (int index = 0; index < this.Count; index++) { if (this[index].Equals(searchValue)) { foundCounter++; } } return (foundCounter); } // Count the number of times an item appears in this sorted ArrayList public int BinarySearchCountAll(object searchValue) { // Sort ArrayList this.Sort( ); bool done = false; int count = 0; // Search for first item int center = this.BinarySearch(searchValue); int left = center - 1; int right = center + 1; int position = -1; if (center >= 0) { // Increment counter for found item ++count; // 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