
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining the Number of Times an Item Appears in a List<T>
|
295
You should note that the Add, Insert, Remove, and RemoveAt methods on the IList
interface of an Array type throw the NotSupportedException, because an array is fixed
in length and these methods will alter the length of the array.
See Also
See the “StackTrace Class” and “IList Interface” topics in the MSDN documenta-
tion. Also see the “Adapter Design Pattern” chapter in Design Patterns (Addison-
Wesley).
5.6 Determining the Number of Times an Item
Appears in a List<T>
Problem
You need the number of occurrences of one type of object contained in a List<T>.
The
List<T> 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
Use the ListEx<T> generic class shown in Example 5-2, which inherits from the
List<T> class in order to extend its functionality. Two methods—CountAll and
BinarySearchCountAll—are added to return the number of times a particular object
appears in a sorted and an unsorted
List<T>.
Example 5-2. Determining the number of times an item appears in a List <T>
using System;
using System.Collections; ...