欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中Arraylist的sort函数用法实例分析

程序员文章站 2023-09-07 19:31:32
本文实例讲述了c#中arraylist的sort函数用法。分享给大家供大家参考。具体如下: arraylist的sort函数有几种比较常用的重载: 1.不带参数 2....

本文实例讲述了c#中arraylist的sort函数用法。分享给大家供大家参考。具体如下:

arraylist的sort函数有几种比较常用的重载:

1.不带参数

2.带一个参数

public virtual void sort(
  icomparer comparer
)

参数

comparer

类型:system.collections.icomparer

比较元素时要使用的 icomparer 实现。

- 或 -

null 引用(visual basic 中为 nothing)将使用每个元数的 icomparable 实现。

示例:

using system;
using system.collections;
public class samplesarraylist {
  public class myreverserclass : icomparer {
   // calls caseinsensitivecomparer.compare with the parameters reversed.
   int icomparer.compare( object x, object y ) {
     return( (new caseinsensitivecomparer()).compare( y, x ) );
   }
  }
  public static void main() {
   // creates and initializes a new arraylist.
   arraylist myal = new arraylist();
   myal.add( "the" );
   myal.add( "quick" );
   myal.add( "brown" );
   myal.add( "fox" );
   myal.add( "jumps" );
   myal.add( "over" );
   myal.add( "the" );
   myal.add( "lazy" );
   myal.add( "dog" );
   // displays the values of the arraylist.
   console.writeline( "the arraylist initially contains the following values:" );
   printindexandvalues( myal );
   // sorts the values of the arraylist using the default comparer.
   myal.sort();
   console.writeline( "after sorting with the default comparer:" );
   printindexandvalues( myal );
   // sorts the values of the arraylist using the reverse case-insensitive comparer.
   icomparer mycomparer = new myreverserclass();
   myal.sort( mycomparer );
   console.writeline( "after sorting with the reverse case-insensitive comparer:" );
   printindexandvalues( myal );
  }
  public static void printindexandvalues( ienumerable mylist ) {
   int i = 0;
   foreach ( object obj in mylist )
     console.writeline( "\t[{0}]:\t{1}", i++, obj );
   console.writeline();
  }
}
/* 
this code produces the following output.
the arraylist initially contains the following values:
    [0]:  the
    [1]:  quick
    [2]:  brown
    [3]:  fox
    [4]:  jumps
    [5]:  over
    [6]:  the
    [7]:  lazy
    [8]:  dog
after sorting with the default comparer:
    [0]:  brown
    [1]:  dog
    [2]:  fox
    [3]:  jumps
    [4]:  lazy
    [5]:  over
    [6]:  quick
    [7]:  the
    [8]:  the
after sorting with the reverse case-insensitive comparer:
    [0]:  the
    [1]:  the
    [2]:  quick
    [3]:  over
    [4]:  lazy
    [5]:  jumps
    [6]:  fox
    [7]:  dog
    [8]:  brown 
*/

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