1. 程式人生 > 實用技巧 >C# ArrayList 方法 IndexOf Insert的使用方法

C# ArrayList 方法 IndexOf Insert的使用方法

  1 using System;
  2 using System.Collections;
  3 
  4 namespace C_9_4
  5 {
  6     class Program
  7     {
  8         private  static void test_1(ArrayList b)
  9         {
 10             int i;
 11             if (b.IndexOf("SB") != -1)
 12             {
 13                 Console.WriteLine("
找到了目標值,下標為{0}\n並輸出資料檢查是否正確", b.IndexOf("SB")); 14 15 for (i = 0; i < b.Count; i++) 16 { 17 Console.WriteLine("{0}", b[i]); 18 } 19 } 20 else 21 { 22 Console.WriteLine("沒有找到對應值
"); 23 } 24 25 } 26 static void Main(string[] args) 27 { 28 //ArrayList.IndexOf 29 //索引方法 30 //格式 ArrayList.IndexOf(Object,Int32_1,Int32_2); 31 //在ArrayList集合裡面尋找Object元素,並且只返回第一個對應元素的下標, 32 //Int32_1 起始元素的下標,Int32_2 搜尋元素的範圍
33 //簡單來講就是,Int32_1確定從第幾個開始查,Int32_2決定往後查幾個資料 34 35 ArrayList a = new ArrayList() { 1, 2, 3, 4, 5, 6, 6, 6, 6 }; 36 Console.WriteLine("{0}", a.IndexOf(6, 2, 5));//5 37 //這裡的返還值是5,雖然我們是從2開始索引的,但是並不會改變結果的下標 38 //並且他只識別到了第一個6,後面的6都沒有計算。 39 40 Console.WriteLine("{0}", a.IndexOf("SB", 2, 5));//-1 41 //當ArrayList.IndexOf索引不到物件的時候,就會返回-1 42 43 //還有另外兩種簡單的辦法 44 //1.ArrayList.IndexOf(Object) 45 //直接在ArrayList中全域性索引來找object 46 Console.WriteLine("{0}", a.IndexOf(6));//5 47 48 //2.ArrayList.IndexOf(Object,Int32_1); 49 //在原有的基礎上添加了Int32_1用來選擇索引資料的起始項 50 Console.WriteLine("{0}", a.IndexOf(6, 4));//5 51 52 //注意:這裡Int32_1的索引位置也是下標,也就是說從前面往後面數的時候,要從0開始 53 // 而後面的int32則是直接的加上數。 54 55 56 //ArrayList.Insert() 57 //講某個元素直接插入在指定位置 58 //格式:ArrayList.Insert(Int32,Object) 59 //Int32就是0的索引位置 60 ArrayList b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 61 //然後為了驗證是否插入成功,我們呼叫te函式進行檢測 62 test_1(b);//物件引用非靜態的靜態,屬性,或方法Program.test_1是必須的 63 //我也不知這是什麼意思,大概對應非靜態的還有別的操作吧,於是我把test_1改成了靜態的 64 //返回的結果是沒有找到 65 66 //b.Insert(10,"SB"); 67 //test_1(b ); 68 //這樣是會報錯的,因為我們設的b是沒有10位的長度的,但是這個方法是怎麼新增的呢》 69 70 b.Insert(0,"SB"); 71 test_1(b); 72 73 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 74 b.Insert(5, "SB"); 75 test_1(b); 76 77 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 78 b.Insert(6, "SB"); 79 test_1(b); 80 81 /* 82 b = new ArrayList() { 5, 4, 2, 44, 8, 9 }; 83 b.Insert(7, "SB"); 84 test_1(b); 85 86 */ 87 88 //通過上述的測試,我們發現,ArrayList.Insert的插入方式 89 //直接插入到Int32的位置,對於其他的資料,前面不動,後面全部後移 90 //並且可以插入到ArrayList.Count有效長度+1位的位置 91 //再往後不能插入,因為沒有開設堆空間了 92 93 } 94 95 } 96 97 98 99 100 101 }