以下透過 Dictionary 實作一個簡單範例
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
Dictionary<string, string> MyDic = new Dictionary<string, string>();
/*
Dictionary<string, string> dctNewWay =
new Dictionary<string, string>()
{
{"Key1", "AAAA"}, {"Key2", "BBBB"},
{"Key3", "CCCC"}, {"Key4", "DDDD"}
};
*/
public Form1()
{
InitializeComponent();
CreateDictionary();
String retrunStr = FindInDictionary("ProductName");
System.Console.WriteLine(retrunStr);
ShowAllInDictionary();
}
// 建立字典
private void CreateDictionary()
{
MyDic.Add("Name", "Chris");
MyDic.Add("Brands", "Apple");
MyDic.Add("ProductName", "iPhone");
MyDic.Add("Time", DateTime.Now.ToString());
}
// 查字典
private String FindInDictionary(String FindMe)
{
if (true == (MyDic.ContainsKey(FindMe)))
{
return MyDic[FindMe];
}
else
{
return "Not Found";
}
}
// 巡整個字典
private void ShowAllInDictionary()
{
foreach (var OneItem in MyDic)
{
Console.WriteLine("Key = " + OneItem.Key + ", Value = " + OneItem.Value);
}
}
}
}
參考出處:
http://code2study.blogspot.tw/2012/01/c-dictionary.html
沒有留言:
張貼留言