C#中的Dictionary的使用

C#中的Dictionary的使用,第1张

C#中的Dictionary的使用

在工作中有时候会用到Dictionary,由于自己之前没用过,参考了一下前人和先辈的实践,仿照着写了一个Test,第一次用还不是很熟练,要多实践练习才能用的得心应手,写代码重在敲键盘,以此为诫。


(主要注意下这个Dictionary的key和value以及添加数据方式)

写了三个方法和一个Student类。


 namespace DictionaryTest
{
class Program
{
static void Main(string[] args)
{
DicSample1();
DicSample2();
DicSample3();
Console.ReadLine();
} public static void DicSample1()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
if (dic.ContainsKey("Item1") == false)
{
dic.Add("Item1", "ZheJiang");
}
if (dic.ContainsKey("Item2") == false)
{
dic.Add("Item2", "ShangHai");
}
else
{
dic["Item2"] = "ShangHai";
}
if (dic.ContainsKey("Item3") == false)
{
dic.Add("Item3", "BeiJing");
}
if (dic.ContainsKey("Item1"))
{
Console.WriteLine("Output:" + dic["Item1"]);
}
//遍历key
foreach (var key in dic.Keys)
{
Console.WriteLine("Output key :{0}" , dic.Keys);
}
//遍历value
foreach (var value in dic.Values)
{
Console.WriteLine("Output value :{0}", dic.Values);
} foreach (var d in dic)
{
Console.WriteLine("Output key:{0}, value:{1}", d.Key, d.Value);
}
} public static void DicSample2()
{
Dictionary<string, string[]> dics = new Dictionary<string, string[]>();
string[] ZheJiang = { "Hangzhou", "Huzhou", "Taizhou", "Wenzhou", "Quzhou" };
string[] AnHui = { "Hefei", "Wuhu", "Huainan", "Fuyang", "Huangshan" };
dics.Add("ZJ", ZheJiang);
dics.Add("AH", AnHui);
for (int i = ; i <= ZheJiang.Count() - ; i++)
{ Console.WriteLine("Output:" + dics["ZJ"][i]); }
for (int j = ; j < AnHui.Count() - ; j++)
{ Console.WriteLine("Output:" + dics["AH"][j]); }
} public static void DicSample3()
{
Dictionary<string, Student> dics = new Dictionary<string, Student>();
Student student = null;
for (int i = ; i < ; i++)
{
student = new Student();
student.Num = i.ToString();
student.Name = "Student Name" + i.ToString();
dics.Add(i.ToString(), student);
}
foreach (var stuItem in dics)
{
Console.WriteLine("Output: key{0},Num{1},Name{2}", stuItem.Key, stuItem.Value.Num, stuItem.Value.Name);
}
}
}
public class Student
{
public string Name { get; set; }
public string Num { get; set; }
}
}

以下是运行结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/587086.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存