2018-10-18集合類 列表List
當我們有跟多型別一樣的資料的時候,我們可以使用集合類來進行管理,比如列表List,我們可以使用列表List很方便的新增資料,刪除資料還有其他操作。
(陣列的缺點:陣列的大小是固定的,不能增加資料)
using System.Collections.Generic;//List需要引入名稱空間
using System.Collections.Generic;
列表內部資料是使用陣列進行儲存的,一個空的列表內部會有一個長度為0的陣列, 當給陣列新增 1-4個數據時,列表的長度會自動擴大為4,如果新增第5個數據的時候,列表會自動擴容為8,如果列表新增第9個數據的時候,列表的長度會自動擴大到16,……,以此類推。當列表中的容量發生變換的時候,它會自動建立一個新的陣列,使用Array.Copy()方法將舊陣列的中的所有元素複製到新的陣列中。為了節省時間,如果事先知道要儲存的資料的個數,就可以利用列表的建構函式指定列表的容量大小。
List<int> intlist = new List<int>(10);//建立一個容量為10的列表,當容量不夠時,每次都會按照原來容量的2倍進行擴容。
using System.Collections.Generic;//List需要引入名稱空間 //空列表的建立 List<int> scoreList1 = new List<int>(); //建立一個空的列表,通過<>宣告列表儲存的資料型別 var scoreList2 = new List<int>(); //建立列表並初始化資料 var scoreList3 = new List<int>() {1, 2, 3, 4, 5, 6, 7, 5, 2, 9, 3, 4}; List<int> scoreList4 = new List<int>() {1, 2, 2, 3}; List<int> intlist = new List<int>(10); scoreList3.Add(50); //列表末尾插入資料 scoreList3.Insert(0, 963); //在指定索引處插入指定資料 scoreList3.Remove(2); //刪除指定資料的第一個匹配項 scoreList3.RemoveAt(3); //刪除指定索引的資料 //scoreList3.Clear();//移除列表中的所有元素 int indexOf = scoreList3.IndexOf(7); //獲取指定資料的第一個元素的索引,如過沒有則返回-1 int lastIndexOf = scoreList3.LastIndexOf(7); //獲取指定資料 從後往前的第一個匹配項的索引,如果沒有返回-1 int cap = scoreList3.Capacity; //獲取列表的容量 int cou = scoreList3.Count; //獲取列表的長度 資料的個數 Console.WriteLine($"{cap},{cou}"); foreach (var i in scoreList3) { Console.Write(i+" "); } Console.WriteLine(); scoreList3.Sort(); foreach (var i in scoreList3) { Console.Write(" "+i); }
//空列表的建立
List<int> scoreList1 = new List<int>(); //建立一個空的列表,通過<>宣告列表儲存的資料型別
var scoreList2 = new List<int>();
//建立列表並初始化資料
var scoreList3 = new List<int>() {1, 2, 3, 4, 5, 6, 7, 5, 2, 9, 3, 4};
List<int> scoreList4 = new List<int>() {1, 2, 2, 3};
List<int> intlist = new List<int>(10);
scoreList3.Add(50); //列表末尾插入資料
scoreList3.Insert(0, 963); //在指定索引處插入指定資料
scoreList3.Remove(2); //刪除指定資料的第一個匹配項
scoreList3.RemoveAt(3); //刪除指定索引的資料
//scoreList3.Clear();//移除列表中的所有元素
int indexOf = scoreList3.IndexOf(7); //獲取指定資料的第一個元素的索引,如過沒有則返回-1
int lastIndexOf = scoreList3.LastIndexOf(7); //獲取指定資料 從後往前的第一個匹配項的索引,如果沒有返回-1
int cap = scoreList3.Capacity; //獲取列表的容量
int cou = scoreList3.Count; //獲取列表的長度 資料的個數
Console.WriteLine($"{cap},{cou}");
foreach (var i in scoreList3)
{
Console.Write(i+" ");
}
Console.WriteLine();
scoreList3.Sort();
foreach (var i in scoreList3)
{
Console.Write(" "+i);
}