实现IComparer

实现IComparer

 

现IComparer ,这样就可以在数组中或其它集合中自定义排序了,要实现其中的方法:

 public int Compare(object x, object y)

 

复制代码

using System;
using System.Collections;//注意using Collections
using System.Collections.Generic;
using System.Text;

namespace ZyyLove2008
{
    
class Program
    {
        
static void Main(string[] args)
        {
            ArrayList list 
= new ArrayList();
            Random random 
= new Random();
            
for (int i = 1; i < 10; i++)
            {
                
int index = random.Next(110);
                Person person 
= new Person("zhang" + index.ToString(), index);
                list.Add(person);
            }
            
foreach (Person personTmp in list)
            {
                Console.WriteLine(personTmp.Name 
+ "\t" + personTmp.Age.ToString());
            }


            list.Sort(
new PersonComparer());
            Console.WriteLine(
"\r\nAfter sorting\r\n");

            
foreach (Person personTmp in list)
            {
                Console.WriteLine(personTmp.Name 
+ "\t" + personTmp.Age.ToString());
            }


            Console.Read();
        }
    }

    
public class Person
    {
        
private string _name;
        
public string Name
        {
            
get
            {
                
return _name;
            }
            
set
            {
                _name 
= value;
            }
        }
        
private int _age;
        
public int Age
        {
            
get
            {
                
return _age;
            }
            
set
            {
                _age 
= value;
            }
        }

        
public Person(string name, int age)
        {
            
this._name = name;
            
this._age = age;
        }
    }

    
public class PersonComparer : IComparer
    {
        
#region IComparer Members
        
/// <summary>
        
/// Compares two objects and returns a value indicating whether one is less than,
        
/// equal to, or greater than the other.
        
/// </summary>
        
/// <param name="x">The first object to compare.</param>
        
/// <param name="y">The second object to compare.</param>
        
/// <returns></returns>
        public int Compare(object x, object y)
        {
            Person personX 
= x as Person;
            
if (personX == null)
            {
                
throw new ArgumentException("x value is not a type of Person""x");
            }
            Person personY 
= y as Person;
            
if (personY == null)
            {
                
throw new ArgumentException("y value is not a type of Person""y");
            }
            
return personX.Age.CompareTo(personY.Age);
        }

        
#endregion
    }
}

posted on 2012-09-28 10:07  baixp2008  阅读(165)  评论(0编辑  收藏  举报

导航