C#非泛型集合类-ArrayList查找元素

为了在数组列表中查找元素,最常使用的是IndexOf或LastIndexOf方法,另外,还可以使用BinarySearch方法执行搜索。
—IndexOf方法从前向后搜索指定的字符串,如果找到,返回匹配的第一项的自0开始的索引,否则,返回-1。
—LastIndexOf方法从后向前搜索指定的字符串,如果找到,返回匹配的最后一项的自0开始的索引,否则,返回-1。

这两个方法各自都有三个重载版本,表示从指定的索引处开始搜索或者是从指定索引处搜索指定长度的字符串。
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
    string[] str ={ "元素一", "元素二", "元素三", "元素四", "元素五", "元素六" };
    ArrayList al = new ArrayList(str);
    int i = al.IndexOf("元素三");
    Console.WriteLine("元素三在集合中的位置是" + i);
    i = al.LastIndexOf("元素五");
    Console.WriteLine("元素五在集合中的位置是" + i);
    Console.ReadLine();
}
}

posted on 2012-06-28 09:30  流星落  阅读(623)  评论(0编辑  收藏  举报

导航