IComparer的简单使用

来源:互联网 发布:手机linux升级安卓 编辑:程序博客网 时间:2024/04/29 09:52

 

/******************************************************************* 

   文件名: IComparer.cs
   摘要: 用IComparer接口做排序的简单例子
   开发平台: Win Xp SP2 + .NET Framework 2.0
   编译环境: CSC.exe 8.0 (in Visual Studio 2005 SDK)
   作者: 88250
   完成日期: 2007-2-4    版本: 1.0
   Blog: 
http://DL88250.ynutx.net
   E-mail: DL88250@gmail.com
   QQ: 845765 or 316281008
                                        
 ******************************************************************
*/ 

using System;
using System.Collections;

namespace SEI.DL88250.SourceCodes.CSharp
{
    
public sealed class StringLengthComparer : IComparer
    {
        
// 实现方法
        public int Compare(object x, object y)
        {
            
string xs = x as string;
            
string ys = y as string;
            
// 判断是否是string
            
// 当然,也可以这样判断:if ((!(x is string) || (!(y is string)))
            if ((xs == null|| (ys == null))
            {
                
throw new ArgumentException("some dire message");
            }
            
// 按字串的长度降序
            int retVal = 1;
            
if (xs.Length > ys.Length)
            {
                retVal 
= -1;
            }
            
else
            {
                
if (xs.Length == ys.Length)
                {
                    retVal 
= 0;
                }
            }
            
return retVal;    
        }
    }

    
public class ComparerTester
    {
        
private static void Display(ArrayList str)
        {
            
foreach (string s in str)
            {
                Console.WriteLine(s);
            }
        }

        
public static void Main(string[] args)
        {
            ArrayList stringList 
= new ArrayList();
            stringList.Add(
"1");
            stringList.Add(
"12");
            stringList.Add(
"123");
            stringList.Add(
"1234");
            Display(stringList);
            
// 按字串的长度降序排序
            stringList.Sort(new StringLengthComparer());
            Display(stringList);
        }
    }
}
原创粉丝点击