Dictionary有Key跟Value,一个Key只能对应一种Value,但一种Value可以对应很多种Key
像是学生座号和成绩,每个人只会对应到一个成绩,但也许有人同时考到相同的分数
下面是官方的范例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith = new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
#output => An element with Key = "txt" already exists.
*/
看不懂的话 可以参考这篇
http://code2study.blogspot.com/2012/01/c-dictionary.html
Dictionary<string, string> MyDic = new Dictionary<string, string>( );
// 建立字典
private void CreateDictionary( )
{
MyDic.Add( "Name", "Jack" );
MyDic.Add( "Blog", "Jack’s Blog" );
MyDic.Add( "Group", "KTV Group" );
}
// 查字典
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 );
}
}
除了上面那種先宣告再Add的方式之外,也可以用底下的方式來直接宣告並產生內容
Dictionary<string, string> dctNewWay =
new Dictionary<string, string>()
{
{"Key1", "AAAA"}, {"Key2", "BBBB"},
{"Key3", "CCCC"}, {"Key4", "DDDD"}
};
另外,值得一提的是,Key跟Value並不限定只能用String,什麼型別都可以,所以你也可以把Class塞到Value,然後其中一個屬性拿出來當作Key,就可以方便的確認有沒有重複的Key,不用塞到SQL才知道。