轻松学习C#的ArrayList类

2019-12-30 11:09:56于丽
  • Console.ReadLine();   }  
  • }   }</span>  

    输出的结果为:未删除前al的元素个数为:5

    删除索引为2后的元素个数为:4

    删除值为abc后的元素个数为:3

    删除自索引为1的两个元素后的元素个数:1

    xyz

    三、ArrayList元素的查找

    ArrayList元素的查找提供了三个方法查找ArrayList中的元素,分别是IndexOf方法,LastindexOf方法和BinarySearch方法。

    (1)、IndexOf方法从前后搜素指定的字符串,如果找到,返回匹配的第一项的自0开始的索引,否则返回-1。其格式为:ArrayList 对象.IndexOf(要索引的字符串)

    (2)、LastIndexOf方法从后向前搜素指定的字符串,如果找到,返回匹配的最后一项自0开始的索引,否则返回-1.其格式为:ArrayList 对象.LastIndexOf(要索引的字符串)

    以上两个方法都有三个重载版本,表示从指定的索引处开始搜索或者是从指定索引处搜素指定长度的字符串。

    (3)、BinarySearch方法使用二分算法从集合中指定的值,并返回找到的从0开始的索引,否则返回-1,其格式为:ArrayList 对象.BinarySearch(要索引的字符串)

    例三、使用上述的方法查找指定的元素

     

     
    1. <span style="font-size:18px;">using System;   using System.Collections;//需要添加的命名空间  
    2. using System.Collections.Generic;   using System.Linq;  
    3. using System.Text;   using System.Threading.Tasks;  
    4.   namespace 动态数组的使用  
    5. {   class Program  
    6. {   static void Main(string[] args)