问题:
你需要能够对一个List<T>中匹配搜索条件的对象进行读取或计数操作。
解决方案:
使用List<T>的四个扩展方法:GetAll,BinarySearchGetAll、CountAll和BinarySearchCountAll。这些方法扩展List<T>类,以返回特定的对象实例或特定对象出现在有序和无序List<T>中的次数,如例2-1所示。
例2-1:确定一个数据项在List<T>中出现的次数
static class CollectionExtMethods
{
#region 2.1 Looking for Specific Items in an List<T>
// The method to retrieve all matching objects in a
// sorted or unsorted List<T>
public static IEnumerable<T> GetAll<T>(this List<T> myList, T searchValue) =>
myList.Where(t => t.Equals(searchValue));
// 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