生活随笔
收集整理的這篇文章主要介紹了
Dictionary泛型集合
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
1 Dictionary<K, V>
1.1 Dictionary<K, V>簡介
關(guān)于Dictionary<K, V>泛型集合:
- Dictionary<K, V>通常稱為字典,<K, V>約束集合中元素類型。
- 編譯時(shí)檢查約束類型,無需裝箱拆箱操作,與哈希表操作類似。
Dictionary<K, V>的存儲(chǔ)結(jié)構(gòu):
1.2 Dictionary<K, V>的創(chuàng)建
使用Add添加:
Dictionary
<string, Student> stuDic1
= new Dictionary<string, Student>();
stuDic1
.Add("VIP1", student1
);
stuDic1
.Add("VIP2", student2
);
stuDic1
.Add("VIP3", student3
);
stuDic1
.Add("VIP4", student4
);
stuDic1
.Add("VIP5", student5
);
使用集合初始化器:
Dictionary
<string, Student> stuDic2
= new Dictionary<string, Student>()
{["VIP1"]=student1
,["VIP2"] = student2
,["VIP3"] = student3
,["VIP4"] = student4
,["VIP5"] = student5
,
};
集合的嵌套:
List
<int> class1List
= new List<int> { 90, 80, 60, 79, 82 };
List
<int> class2List
= new List<int> { 93, 85, 60, 79, 82 };
List
<int> class3List
= new List<int> { 92, 80, 60, 89, 88 };Dictionary
<string
, List
<int>> classList
= new Dictionary<string
, List
<int>>()
{["軟件1班"]= class1List
,["軟件2班"] = class2List
,["軟件3班"] = class3List
};
1.3 Dictionary<K, V>的訪問和遍歷
通過key訪問value:
Student student
= stuDic1
["VIP3"];
Console
.WriteLine(student
.StudentName
);
遍歷key:
foreach
(string key in stuDic1
.Keys
){Console
.WriteLine(key
);}
遍歷values:
foreach
(Student item in stuDic1
.Values
)
{Console
.WriteLine(item
.StudentId
+"\t" + item
.StudentName
+ "\t" + item
.Age
);
}
參考資料:
.NET/C#工控上位機(jī)VIP系統(tǒng)學(xué)習(xí)班【喜科堂互聯(lián)教育】
總結(jié)
以上是生活随笔為你收集整理的Dictionary泛型集合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。