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