小記一下,再 C++ std::map::find常用這指命來取得對應的資訊,只要結果不等於 map::end,就表示有找到對應的值,但在 C# 當中,如果直接使用 key 來驗證是否為 null,則會造成 nullable exception,學習長知識一下。
using System;
using TestConsol.MyLibs;
namespace TestConsol
{
class Program
{
static void Trace(T param)
{
Console.WriteLine(param);
}
static void Main(string[] args)
{
Trace("test");
TestDic temp = new TestDic();
temp.AddData("a","is a");
temp.AddData("a", "is b");
Console.WriteLine("Value ==> {0}", temp.HasDataByKey("a") );
Console.WriteLine("Value ==> {0}", temp.GetDataByKey("a") );
Console.ReadKey(true);
}
}
}
取資料當然也可以使用 return dicData.FirstOrDefault( x => x.Key == _key ).Value; 但這樣會變成使用 IEnumAble iterator,如果是使用 List 應該就很建議使用。原因應該很多達人都有分享,不再累述。
using System.Collections.Generic;
namespace TestConsol.MyLibs
{
/// <summary>
/// @link http://www.dotnetperls.com/dictionary
/// @link http://msdn.microsoft.com/zh-tw/library/xfhwa508(v=VS.95).aspx
/// </summary>
class TestDic
{
/// <summary>
/// 資料儲存區
/// </summary>
private Dictionary<string, string> dicData = null;
public TestDic() {
dicData = new Dictionary<string, string>();
}
/// <summary>
/// 加入資訊
/// </summary>
/// <param name="value"></param>
public void AddData( string _key, string _value ){
if (!HasDataByKey(_key))
{
dicData.Add(_key, _value);
}
else {
dicData[_key] = _value;
}
}
/// <summary>
/// 經由 Key 取得資料
/// </summary>
/// <param name="_key">ID 值</param>
/// <returns></returns>
public string GetDataByKey(string _key)
{
//return dicData.FirstOrDefault( x => x.Key == _key ).Value;
if (HasDataByKey(_key))
{
return dicData[_key];
}
return null;
}
/// <summary>
/// 是否已經有這筆資料
/// </summary>
/// <param name="_key"></param>
/// <returns>true 則表示有這筆資料</returns>
public bool HasDataByKey(string _key) {
return dicData.ContainsKey(_key);
}
}
}
沒有留言:
張貼留言