确定一项出现在List中的次数

来源:互联网 发布:昆仑墟进阶数据 编辑:程序博客网 时间:2024/05/22 14:12
   在List<T>包含了一些查找某一项的方法(如:Contains和BinarySearch),但是,这些方法无法实现查找重复项,所以利用以下2种方法(CountAll和BinarySearchCountALL)实现 返回一个特定对象出现在有序和无序List<T>中的次数。
 
using System;
using System.Collections;
using System.Collections.Generic;

public class ListEx<T> : List<T>
{
    
// Count the number of times an item appears in this
    
// unsorted or sorted List<T>
    public int CountAll(T 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 List<T>.
    public int BinarySearchCountAll(T searchValue)
    
{
        
// Search for first item.
        int center = this.BinarySearch(searchValue);
        
int left = center;
        
while (left >0 && this[left-1].Equals(searchValue))
        
{
            left 
-= 1;
        }


        
int right = center;
        
while (right < (this.Count - 1&& this[right+1].Equals(searchValue))
        
{
            right 
+= 1;
        }


        
return (right -left) + 1;
    }

}



以下测试代码:
class Test
    
{
        
static void Main()
        
{
            ListEx
<int> arrayExt = new ListEx<int>();
            arrayExt.Add(
-2);
            arrayExt.Add(
-2);
            arrayExt.Add(
-1);
            arrayExt.Add(
-1);
            arrayExt.Add(
1);
            arrayExt.Add(
2);

            arrayExt.Add(
2);
            arrayExt.Add(
2);
            arrayExt.Add(
2);
            arrayExt.Add(
3);
            arrayExt.Add(
100);
            arrayExt.Add(
4);
            arrayExt.Add(
5);

            Console.WriteLine(
"--CONTAINS TOTAL--");
            
int count = arrayExt.CountAll(2);
            Console.WriteLine(
"Count2: " + count);

            count 
= arrayExt.CountAll(3);
            Console.WriteLine(
"Count3: " + count);

            count 
= arrayExt.CountAll(1);
            Console.WriteLine(
"Count1: " + count);

            Console.WriteLine(
" --BINARY SEARCH COUNT ALL--");
            arrayExt.Sort();
            count 
= arrayExt.BinarySearchCountAll(2);
            Console.WriteLine(
"Count2: " + count);

            count 
= arrayExt.BinarySearchCountAll(3);
            Console.WriteLine(
"Count3: " + count);

            count 
= arrayExt.BinarySearchCountAll(1);
            Console.WriteLine(
"Count1: " + count);
        }

    }


CountAll方法使用For循环线性查找,而BinarySearchCountAll方法使用了二分查找。
CountAll方法接受一个类型为Object的搜索值,这个方法再统计该搜索值出现在ListEx<T>类中的次数,此方法有序或者无序都可以使用,如果ListEx<T>为有序的(ListEx<T>通过调用Sort方法已经排序),可以用BinarySearchCountAll方法来提高搜索效率。与迭代处理这个ListEx<T>相比,这个方法的速度要快,随着ListEx<T>规模的增长,效率提升。
原创粉丝点击