C#入門基礎文法總結(數組和集合)

來源:互聯網
上載者:User

標籤:迴圈   輸出   合規   [1]   維數   類型   string   構造   nbsp   

一、數組

1、一維數組的建立:

        數組元素資料類型[] 數組名字;  如 int[]arr; String[] arr;

2、一維數組的初始化

①  int[] arr=new int[3]; int[0]=1;int[1]=2;int[2]=3;

② int[] arr=new int[]{1,2,3};

③int[]arr={1,2,3};

3、二維數組的建立:

      ① 資料類型[, ]數組名  int[, ]a=new int[2,4];2行4列的數組。適合規則數組

      ②資料類型[][] 數組名 int[][] a=new int[2][];int[0]=new int[2];表示第一行兩列。int[1]=new int[3];表示第二行三列。注意:此種命名方法不能指定列數。先指定行數後給每一行指定列數

4、二維數組的初始化

① int[, ] arr=new int[2,2]; arr[0,0]=0;arr[0,1]=1;.....

②int[][] arr=new int[2][]; arr[0]=new int[]{0,1};arr[1]=new int[]{1,2}; 注意:先確定行,每一行都是一個一維數組。

③int[, ] arr=new int[2,2]{{12,0},{45,10}};  int[, ] arr=new int[]{{12,0},{45,10}};int[, ] arr={{12,0},{45,10}};

二、數組的操作

1、一維數組的輸入與輸出:使用單層迴圈

2、二維數組輸入與輸出:使用雙層迴圈

3、foreach方法遍曆數組:foreach(int number in arr)

4、數組的排序:升序sort()從小到大,reverse()反向排序;

5、冒泡排序:基本思想比較相鄰的兩個數,滿足條件,較小的數排在數組前面,較大的數排在數組後面。需要使用雙層迴圈,//外層迴圈代表比較輪數,5個數要比較4輪.//內從迴圈代表比較次數,第一輪比較4次,第二輪比較3次.

6、選擇排序:基本思路是把滿足條件的元素與指定位置的元素位置交換。雙層for迴圈實現,外層迴圈比較輪數。每一輪找出一個最小值,進行位置互換。內層迴圈找到最小值的索引。

三、ArrayList類

 1、ArrayList的三種構造器:

①使用預設構造器

ArrayList List=new ArrayList();

for(int i=0;i<10;i++){List.Add()}

②用一個IColliction物件建構

ArrayList List=new ArrayList(arryName)

③用指定的大小初始化內部數組

ArrayList List=new ArrayList(n);

2、ArrayList元素的添加

①add方法 在末尾處添加元素

②insert 方法 insert(index,value)index索引,value值

3、ArrayList元素刪除

①Clear方法移除所有元素

②remove方法 移除指定對象的第一個對象 remove(Obj)

③RemoveAt方法 RemoveAt(int index)

④RemoveRange(index,count)index開始的索引 count移除的個數

4、ArrayList遍曆數組

foreach()

5、ArrayList元素的尋找

①Contains方法 Contains(Obj)

②IndexOf方法返回首次出現的位置

③LastIndexOf方法最後一個匹配項出現的位置

四、Hashtable類

1、Hashtable 元素的添加

add(key,value)key鍵value值

2、Hashtable元素的移除

①Clear方法

②Remove方法 Remove(key)

3、Hashtable的遍曆 使用DictionnaryEntry類型進行遍曆

4、Hashtable元素的尋找

①Contains方法 Contains(key)

②ContainsValue方法 ContainsValue(value)

 

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.