C#中Arraylist的sort函数用法实例分析
作者:dongfengkuayue
这篇文章主要介绍了C#中Arraylist的sort函数用法,较为详细的分析了ArrayList的sort函数的功能、定义及具体使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
本文实例讲述了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#程序设计有所帮助。
您可能感兴趣的文章:
- C#常见的几种集合 ArrayList,Hashtable,List<T>,Dictionary<K,V> 遍历方法对比
- C#检查指定对象是否存在于ArrayList集合中的方法
- C#中Array与ArrayList用法及转换的方法
- C#中ArrayList的使用方法
- 浅析C#中数组,ArrayList与List对象的区别
- C#.Net ArrayList的使用方法
- C#查找对象在ArrayList中出现位置的方法
- c# ArrayList的使用方法小总结
- C#中数组、ArrayList、List、Dictionary的用法与区别浅析(存取数据)
- C#生成随机ArrayList的方法
- C#中数组、ArrayList和List三者的区别详解及实例
- C#入门教程之集合ArrayList用法详解
