ICompare与Sort

今天参与了一个讨论关于对Dictionary排序问题:

http://community.youkuaiyun.com/Expert/topic/5682/5682646.xml?temp=2.558535E-02 

小结如下:

  • .net framework2.0 可以使用范型对简单数据类型进行比较排序,例如:
                  // GetUniqueRandom可以获得一组随机数 返回List<int>
                List < int >  uRand  =  GetUniqueRandom();  
                uRand.Sort();
                Enumerator objEnumT 
=  ((IEnumerable)uRand).GetEnumerator();
                
int  i  =   0 ;
                
while  (objEnumT.MoveNext())
                
{
                      Object obj 
= objEnumT.Current;
                      Console.WriteLine(
" [{0}]: {1}", (Int32)i++, (int)obj);
                }


 

  • .net framework 1.1不支持反省范型,可以将hashtable中的数字输出到arraylist中然后排序,但要重写ICompare接口。先给出一个例子:

 

                Hashtable ht  =   new  Hashtable();
                
int  index  =   0 ;
                
int [] uRand  =  GetUniqueRandom();
                
foreach ( int  rand  in  uRand)
                
{
                    index 
++ ;
                    ht.Add(index, rand);
                }


                ArrayList al 
=   new  ArrayList(ht);
                IComparer myComparer 
=   new  myComparerClass();
                al.Sort(myComparer);
                
                IEnumerator objEnum 
=  ((IEnumerable)al).GetEnumerator();

                
int  i  =   0 ;
                
while  (objEnum.MoveNext())
                
{
                    Object obj 
= objEnum.Current;
                    Console.WriteLine(
" [{0}]: {1}", (Int32)i++, ((DictionaryEntry)obj).Value);
                }

由于ArrayList 排序Sort方法需要传入排序的方式,即Icompare接口。下面根据MSDN上的描述:

http://msdn2.microsoft.com/en-us/library/system.collections.icomparer.compare(VS.71).aspx

http://msdn2.microsoft.com/en-us/library/system.collections.icomparer.aspx

可知:需重写int   IComparer.Compare(Object x, Object y)方法。

Return Value
ValueCondition
Less than zerox is less than y.
Zerox equals y.
Greater than zerox is greater than y.
故对以上代码实现了一个ICompare:
         public   class  myComparerClass : IComparer
        
{

            
// 比较Value,不比较key
            int IComparer.Compare(Object x, Object y)
            
{
                DictionaryEntry X 
= (DictionaryEntry)x;
                DictionaryEntry Y 
= (DictionaryEntry)y;
                
//return ((int)X.Value < (int)Y.Value ? (int)X.Value : (int)Y.Value);
                if ((int)X.Value == (int)Y.Value)
                    
return 0;
                
else if ((int)X.Value > (int)Y.Value)
                    
return 1;
                
else
                    
return -1;
            }


        }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值