December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to retrieve every object contained in a List<T> that matches a search criterion. The List<T> 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 a List<T>, you must write your own routine.
Use the GetAll and BinarySearchGetAll methods shown in Recipe 5.5, which extend the List<T> class. These methods return an array of all the matching objects found in a sorted or unsorted List<T>.
Example 5-3. Retrieving all instances of a specific item in a List<T>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
static class CollectionExtMethods
{
// The method to retrieve all matching objects in a
// sorted or unsorted ListEx<T>
public T[] GetAll(T searchValue)
{
List<T> foundItem = new List<T>();
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 ListEx<T>
public static T[] BinarySearchGetAll<T>(this List<T> myList, T searchValue) { List<T> RetObjs = new List<T>(); // Search for first item. int center = myList.BinarySearch(searchValue); if (center > 0) { RetObjs.Add(myList[center]); int left = center; while (left > 0 && myList[left - 1].Equals(searchValue)) { left -= 1; RetObjs.Add(myList[left]); } int right = center; ...Read now
Unlock full access