C#中的Array和ArrayList

來源:互聯網
上載者:User

一、Array的一些方法

int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };

Console.Write("排序之前order: ");

foreach (int i in nums)

Console.Write(i + " ");Console.WriteLine();

int before = Array.IndexOf(nums, 14);

Console.WriteLine("before sort 14 index is " + before);

//排序之前在數組中的序號

Array.Sort(nums);//靜態方法對數組進行排序

Console.Write("排序之後order:   ");

foreach (int i in nums)Console.Write(i + " ");

//輸出數組int index = Array.BinarySearch(nums, 14);

//尋找的序號Console.WriteLine("the index of is is" + index);

Console.WriteLine();string[] strArray = new string[] 

{ "75.3", "25.999", "105.25" };

//類型轉換double[] doubleArray = Array.ConvertAll

<string, double>(strArray, Convert.ToDouble);

//實作類別型的轉換

Console.Write("Converted to doubles: ");

Array.ForEach<double>(doubleArray, delegate(double x)

{ Console.Write(x + " "); });//委託事件

程式結果截圖

 

二、ArrayList

Array是個靜態數組,一旦數組大小在初始化過程中確定了在後面就不能修改了,也不能對數組中的元素進行增加和刪除.這不是很靈活,為此C#提供了ArrayList用來處理動態數組.,

ArrayList在建立以後可以根據實際需要進行元素的增刪.這個是非常好用了..我們先看下ArrayList的建構函式

ArrayList al = new ArrayList(); 

再來看一個簡單的例子:

ArrayList al = new ArrayList(); 

Console.WriteLine

("Initial number of elements: " + al.Count); 

Console.WriteLine("Adding 6 elements"); 

// Add elements to the array list 

al.Add('C'); 

al.Add('A'); 

al.Add('E'); 

al.Add('B'); 

al.Add('D'); 

al.Add('F');

al.Remove('A');//刪除一個元素

Console.WriteLine(al.Count);

al.Add('a');//增加一個元素

Console.WriteLine(al.Count);

al[0] = 'X';//修改數組元素

al[1] = 'Y';

al[2] = 'Z';

//刪除一個元素後數量變為5,增加一個後元素的數量為6

 

那麼現在我們再來建立一個數位ArrayList來學習下它的方法;

ArrayList al = new ArrayList(); 

// Add elements to the array list 

al.Add(155);  al.Add(413); 

al.Add(-41);  al.Add(818); 

al.Add(31); al.Add(191); 

Console.Write("Original contents: "); 

foreach(int i in al) 

Console.Write(i + " "); 

Console.WriteLine("\n"); 

// Sort 排序

al.Sort(); 

Console.Write("Contents after sorting: "); 

foreach(int i in al) 

Console.Write(i + " "); 

Console.WriteLine("\n"); 

Console.WriteLine("Index of 413 is " + 

al.BinarySearch(413));

上圖是輸出的結果,這次對ArrayList 只做了個簡單的介紹,下次對ArrayList提供的執行個體方法和靜態方法做個詳細的介紹.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.