C# 的 Dictionary
C# 的 Dictionary
與 C++ 的 map 非常相似,只是沒有排序功能
class DictionaryTest
using System;
using System.Collections.Generic;
class DictionaryTest
{
private Dictionary<int, string> _dicTest = new Dictionary<int, string>();
public DictionaryTest()
{
_dicTest.Clear();
}
public bool IsExist(int idx)
{
//TryGetValue 比 ContainsKey 還要快
string str = null;
if (_dicTest.TryGetValue(idx, out str))
return true;
return false;
}
public void AddData(int idx, string str)
{
if(!IsExist(idx))
_dicTest[idx] = str;
}
public string GetData(int idx)
{
string str = null;
if (_dicTest.TryGetValue(idx, out str))
return str;
else
return null;
}
public void RemoveOneData(int delIdx)
{
_dicTest.Remove(delIdx);
}
public void RemoveMoreData(int[] delIdx)
{
for (int i = 0; i < delIdx.Length; i++)
RemoveOneData(delIdx[i]);
}
public void ClearDictionary()
{
_dicTest.Clear();
}
public Dictionary<int, string> GetDictionary()
{
return _dicTest;
}
public void PrintDictionary()
{
foreach (KeyValuePair<int, string> item in _dicTest)
{
Console.WriteLine("_dicTest[" + item.Key + "] = " + item.Value);
}
Console.WriteLine("");
}
public void RemoveMoreData_Wrong(int[] delIdx)
{
//這是錯誤示範
for (int i = 0; i < delIdx.Length; i++)
{
//千萬不可以在同一個迴圈裡刪除2個以上的元素
foreach (KeyValuePair<int, string> item in _dicTest)
{
if (IsNeedDelete(item.Key, delIdx[i]))
_dicTest.Remove(item.Key);
}
}
}
private bool IsNeedDelete(int idx, int delIdx)
{
if (idx == delIdx)
return true;
return false;
}
}
main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace csDictionaryTest01
{
class Program
{
static void Main(string[] args)
{
DictionaryTest Dic = new DictionaryTest();
//---------------------------------------------
Console.WriteLine("AddData :");
Dic.AddData(1, "ONE");
Dic.AddData(2, "TWO");
Dic.AddData(3, "THREE");
Dic.AddData(4, "FOUR");
Dic.AddData(5, "FIVE");
Dic.PrintDictionary();
//---------------------------------------------
Console.WriteLine("Dic.IsExist(6) = " + Dic.IsExist(6));
Console.WriteLine("Dic.IsExist(1) = " + Dic.IsExist(1));
Console.WriteLine("");
//---------------------------------------------
Console.WriteLine("Dic.GetData(2) = " + Dic.GetData(2));
Console.WriteLine("");
//---------------------------------------------
Console.WriteLine("After remove data[2] :");
Dic.RemoveOneData(2);
Dic.PrintDictionary();
//---------------------------------------------
Console.WriteLine("After remove data[3] and data[5] :");
int[] delIdx = new int[] { 3, 5 };
Dic.RemoveMoreData(delIdx);
//Dic.RemoveMoreData_Wrong(delIdx); //這是錯誤示範
Dic.PrintDictionary();
//---------------------------------------------
Console.WriteLine("After ClearDictionary :");
Dic.ClearDictionary();
Dic.PrintDictionary();
Console.Read();
}
}
}
參考資料
http://msdn.microsoft.com/zh-tw/library/xfhwa508(v=vs.110).aspx
http://www.dotnetperls.com/dictionary
http://www.dotnetperls.com/sort-dictionary
留言
張貼留言