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


<<:  [Day-2] 探索Dev C++

>>:  [iT铁人赛Day11]JAVA回圈

C# 入门 SSH 连接

对于熟悉 Python 的人,应该了解 Python 之所以简单,易学,是因为包含了很多第三方的库。...

用 tkinter 实现选择路径打开 excel ,并用 tree view 显示

引注资料 https://blog.csdn.net/weixin_43184622/article...

python3-日历

在python3中,想要制作日历有两种方式,先介绍第一种: -直接使用python中calendar...

要怎麽计算「顾客终身价值(LTV)」?

什麽是LTV Lifetime value 的头字母简称。中文翻为「顾客终身价值」。 意思是,平均而...

[机派X] Day 12 - 那些年还没介绍的无人机部件

引言 今天是机派X系列文章的第十二天。 今天会接续昨天的部件介绍,将剩下几个重要的部件介绍给大家。 ...