December 2007
Intermediate to advanced
896 pages
19h 57m
English
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.
Use the two methods defined in Recipe 5.4—CountAll and BinarySearchCountAll. These methods extend the List<T> class 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; using System.Collections.Generic; using System.Linq; static class CollectionExtMethods{ // Count the number of times an item appears in this // unsorted or sorted List<T> public static int CountAll<T>(this List<T> myList, T searchValue) { return ((from t in myList where t.Equals(searchValue) select t).Count()); } // Count the number of times an item appears in this sorted List<T>. public static int BinarySearchCountAll<T>(this List<T> myList, T searchValue) { // Search for first item. int center = myList.BinarySearch(searchValue); int left = center; while (left < 0 && myList[left-1].Equals(searchValue)) { left -= 1; } int right = center; while (right < (myList.Count - 1) && myList[right+1].Equals(searchValue)) { right += ...Read now
Unlock full access