10、C#基礎整理(集合)

來源:互聯網
上載者:User

標籤:style   blog   ar   io   color   sp   for   strong   on   

集合1、集合的引用
using System.Collections;//添加類
2、定義集合(ArrayList 或 Array)
ArrayList arr = new ArrayList();
3、添加資料(可以放多種不同資料類型,但最好只放一種)(一)單個資料

方法1:add增加

arr.Add(3);arr.Add(5);arr.Add("hello");

 

輸出結果:

Console.WriteLine("add[0]:"+arr[0]); //通過添加元素的先後順序產生從0開始的索引,通過索引讀取資料,輸出結果為"3"Console.WriteLine("add[1]:" + arr[1]);//5Console.WriteLine("add[2]:"+arr[2]);//hello

方法2:insert插入,使從索引所示的資料開始的資料向後移動一位

arr.Insert(1, 17);//Insert(索引,插入的資料)

輸出結果:

Console.WriteLine("insert[0]"+arr[0]);//3Console.WriteLine("insert[1]" + arr[1]);//17Console.WriteLine("insert[2]" + arr[2]);//5Console.WriteLine("insert[3]" + arr[3]);//hello
(二)數組:

1、追加一組資料addrange

int[] shuzu = new int[3] { 6, 7, 8 };arr.AddRange(shuzu);

遍曆:

foreach (object o in arr)//因為集合中可能會有多種資料,所以要用object(基類)進行遍曆,所有類型都可以轉化為這個類型{Console.WriteLine("遍曆1:" + o);}

2、從指定索引開始插入一組資料InsertRange

arr.InsertRange(2, shuzu);//遍曆foreach (object o in arr){Console.WriteLine("遍曆2:" + o);}
4、移除資料:(只移除第一個匹配項)

(一)移除指定資料(值):Remove

arr.Remove(17);//移除值為17的資料foreach (object o in arr){Console.WriteLine("Remove後:" + o);}

(二)移除指定索引位置的元素:RemoveAt

arr.RemoveAt(2);Console.WriteLine("Remove後索引為[3]的資料:"+arr[3]);
5、排序:

(1)sort:自動按升序排列

ArrayList arr1 = new ArrayList();for (int i = 0; i < 5; i++){arr1.Add(int.Parse(Console.ReadLine()));}arr1.Sort();foreach (object o in arr1){Console.WriteLine("升序sort:"+o);}

(2)Reverse:翻轉集合的排序(使其變為降序)

arr1.Reverse();foreach (object o in arr1){Console.WriteLine("翻轉reverse後降序:"+o);}
6、集合的屬性:

count:返回集合裡面有多少元素

Console.WriteLine("元素個數為:" + arr1.Count);
7、返回索引IndexOf
Console.WriteLine("hello所在的索引為:"+arr.IndexOf("hello"));//只返回第一個匹配項所在的索引Console.WriteLine("hello所在的最後一個匹配項所在的索引為:" + arr.LastIndexOf("hello"));//返回最後一個匹配項所在的索引

**插入的數組索引也是按單個資料排列的,如:插入一組三個數的數組,會建立三個索引。

8、contains:判斷是否有某個元素,返回bool值

arr.Contains(1);

9、清空集合

arr.Clear();

 

10、C#基礎整理(集合)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.