好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用IComparer自定义List类实现排序的方法

本文实例讲述了C#使用IComparer自定义List类实现排序的方法。分享给大家供大家参考。具体如下:

List类中不带参数的Sort函数可以用来为List类中的元素排序,但如果List类中的元素类型本身不能直接进行比较(如自定义的struct和很多class),或是希望采用更加灵活的自定义比较方式,可以通过继承了IComparer接口的函数来解决。

代码示例如下:

1)声明一个类

?

/// <summary>

/// 人物类

/// </summary>

public class Person

{

   public string Name;

   public int Age;

   public override string ToString()

   {

     return "Name: " + Name + " Age: " + Age;

   }

}

2)声明一个继承了接口IComparer的类

?

/// <summary>

/// 比较人物类实例大小,实现接口IComparer

/// </summary>

public class PersonComparer : IComparer<Person>

{

   public int Compare(Person x, Person y)

   {

     if (x == null && y == null ) return 0;

     if (x == null ) return -1;

     if (y == null ) return 1;

     //TODO:Person类实例X与Y的比较规则

     //按姓名由小到大排列,姓名相同的人年龄大的在前

     {

       int temp = string .Compare(x.Name, y.Name);

       if (temp > 0) return -1;

       else if (temp < 0) return 1;

       if (x.Age > y.Age) return 1;

       if (x.Age < y.Age) return -1;

     }

     return 0;

   }

}

3)Main函数,建立一个List,并使用刚建立的PersonComparer类中的规则对List进行排序

?

static void Main( string [] args)

{

   List<Person> a = new List<Person>();

   a.Add( new Person() { Name = "Tsybius" , Age = 23 });

   a.Add( new Person() { Name = "Galatea" , Age = 21 });

   a.Add( new Person() { Name = "Lucius" , Age = 22 });

   a.Add( new Person() { Name = "Septimus" , Age = 22 });

   a.Add( new Person() { Name = "Octavius" , Age = 22 });

   a.Add( new Person() { Name = "Lucius" , Age = 24 });

   //输出a中全部元素

   Console.WriteLine( "排序前" );

   foreach (var v in a)

   {

     Console.WriteLine(v.ToString());

   }

   Console.WriteLine( "-" );

   //对a进行排序

   a.Sort( new PersonComparer());

   //输出a中全部元素

   Console.WriteLine( "排序后" );

   foreach (var v in a)

   {

     Console.WriteLine(v.ToString());

   }

   Console.WriteLine( "-" );

   Console.ReadLine();

}

4)程序运行示例

希望本文所述对大家的C#程序设计有所帮助。

dy("nrwz");

查看更多关于C#使用IComparer自定义List类实现排序的方法的详细内容...

  阅读:65次