iT邦幫忙

2021 iThome 鐵人賽

DAY 6
4
自我挑戰組

C# 學習之旅系列 第 6

ASP.NET MVC 從入門到放棄 (Day6) -C#集合、IEnumerable ICollection IList介紹

接著來講講常用的集合寫法....

Array(陣列): 是相同型別的集合 透過引索去取得元素 長度是固定的
List(串列): 是相同型別的集合 透過引索去取得元素 長度是任意的
Dictionary(字典): 是鍵值的集合 透過鍵去取得值 長度是任意的

集合簡單來講就是宣告一個變數 包含了一組數字

Array 寫法 (需一開始宣告固定長度)

int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 };

可利用foreach 將 集合裡面數字取出

foreach (int i in myIntArray)
{
   Console.Write("\t{0}", i);
}

ArrayList 寫法

ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");

可利用foreach 將 集合裡面數字取出

foreach (Object obj in myAL)
{
   Console.Write("   {0}", obj);
}

List T 寫法(常用) 通常會將class給丟進去

public class Part
{
   public string PartName { get; set; }

   public int PartId { get; set; }
}
     
List<Part> parts = new List<Part>();
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 });

後續會有一篇簡單講解泛型用途/images/emoticon/emoticon32.gif

可利用foreach 將 集合裡面取出

foreach (Part aPart in parts)
{
   Console.WriteLine(aPart);
}

註解

List<Part> parts  我宣告一個parts 變數 那個變數是 List型別 而且型別裡面是Part Class
new List<Part>();  要從電腦記憶體生成List 變數 需要用new

當然可以不一定要放class string or int 其他型別也行.../images/emoticon/emoticon37.gif

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

可利用foreach 將 集合裡面取出

foreach (string dinosaur in dinosaurs)
{
   Console.WriteLine(dinosaur);
}

註解new完之後 系統會自行判斷無用途會啟動GC機制/images/emoticon/emoticon77.gif

Dictionary 寫法 可自行建立自己要的索引

Dictionary<string, string> MyDic = new Dictionary<string, string>();
MyDic.Add("Name", "Jack");
MyDic.Add("Blog", "Jack’s Blog");
MyDic.Add("Group", "KTV Group");

參考網址

另外來講講IEnumerable ICollection IList 這3種差異 ,因為後面MVC 架構會很常出現...

IEnumerable 可唯讀
ICollection 可新增、修改、刪除 (包含IEnumerable 功能)
IList 可排序(包含IEnumerable、 ICollection功能)

簡單來講List是所有功能都有但效能最差
IEnumerable 只能唯讀但效能最好

按照功能排序:List 〈 IList 〈 ICollection 〈 IEnumerable
按照性能排序:IEnumerable《ICollection《IList《List


上一篇
ASP.NET MVC 從入門到放棄 (Day5) -C# 判斷式 迴圈介紹
下一篇
ASP.NET MVC 從入門到放棄 (Day7) -C#物件導向介紹(封裝 繼承 多型
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Patrick_Star
iT邦新手 5 級 ‧ 2022-08-23 15:46:07

感謝你的日誌
學習中...

我要留言

立即登入留言