1. 程式人生 > >C#入門7.11——ArrayList類中元素的遍歷與查詢

C#入門7.11——ArrayList類中元素的遍歷與查詢

遍歷:

foreach語句,object型別

object:ArrayList中儲存的型別不一定一支,也不一定能夠完全轉換,所以為了避免出錯,我們採用object型別。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;//引用名稱空間
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList myArrayList = new ArrayList(2);
            myArrayList.Add("數字");
            int[] myintArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            myArrayList.AddRange(myintArray);
            myArrayList.Add("字串");
            string[] mystringArray = { "張三","李四","王五","趙六"};
            myArrayList.AddRange(mystringArray);
            //以下實現ArrayList遍歷
            foreach (object outElement in myArrayList) Console.Write(outElement+"\t");
            Console.WriteLine();
            //元素的查詢
            //有三個方法
            //1.IndexOf(要查詢的元素),返回一個索引整數值,如果查詢不到,返回-1        
            Console.WriteLine(myArrayList.IndexOf("張三"));

            //2.LastIndexOf(要查詢的元素)返回一個最後一次出現的索引整型值,否則,返回-1
            Console.WriteLine(myArrayList.LastIndexOf("張三"));

            //3.BinarySearch();查詢不到,返回-1  資料型別過多會報異常。
            //Console.WriteLine(myArrayList.BinarySearch("張三"));
            ArrayList newArrayList = new ArrayList();
            newArrayList.AddRange(myintArray);
            newArrayList.Add(10);
            newArrayList.Add(20);
            foreach (object outElement in newArrayList) Console.Write(outElement + "\t");
            Console.WriteLine();
            Console.WriteLine(newArrayList.BinarySearch(20));

            Console.ReadKey();
        }

    }
}