C#之(集合&字典&foreach的循环遍历)
发布日期:2021-06-30 10:17:50 浏览次数:2 分类:技术文章

本文共 1422 字,大约阅读时间需要 4 分钟。

创 建 L i s t \color{Red}创建List List

L i s t 指 定 类 型 , 类 似 数 组 但 速 度 更 快 更 灵 活 List指定类型,类似数组但速度更快更灵活 List,

List<类型> 变量名 = new List<类型>();

List
people = new List
();int number = 2;people.Add(number);//添加元素int now = people[0];//类似索引的方法访问元素people.RemoveAt(0);//删掉索引为0的元素

创 建 d i c t i o n a r y 字 典 \color{orange}创建dictionary字典 dictionary

字 典 的 索 引 是 键 , 内 容 是 值 字典的索引是键,内容是值 ,

Dictionary<键的类型,值的类型> 变量名 = new Dictionary<键的类型,值的类型>();

Dictionary
dic1 = new Dictionary
();dic1.Add(1, "100分");dic1.Add(2, "101分");//使用Add方法添加元素dic1[3] = "102分";//使用键索引的方法添加元素Dictionary
dic2 = new Dictionary
//键值对的类型都是string{ {"我","无敌"},//每个元素的初始化用{}包裹起来 { "你","无敌" }, { "其他人","有敌"}};string value = dic2["我"];//用键索引取得值dic2.Remove("我");//用键索引删除值

f o r e a c h 的 循 环 遍 历 \color{Red}foreach的循环遍历 foreach

int[] a = { 1, 2, 3 };foreach(int item in a)//每次循环item都等于a数组的下一个元素{    MessageBox.Show(item.ToString() );//展示出来看看}

遍历list

List
intlist = new List
() { 1, 2, 3 };foreach (int item in intlist) MessageBox.Show(item.ToString());

遍历dictionary

Dictionary
dic = new Dictionary
{ { "我","TXDY" }, { "你","TXDY"}, { "其他人","TXDE"}};foreach(KeyValuePair
item in dic)//注意类型是KeyValuePair{ string key = item.Key; string value = item.Value; MessageBox.Show(value);}

转载地址:https://issue-is-vegetable.blog.csdn.net/article/details/107168746 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C#之(创建类,类方法)
下一篇:E. Packmen(贪心+二分[注意细节])

发表评论

最新留言

很好
[***.229.124.182]2024年04月30日 06时54分10秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章