Dictionary擴(kuò)展基礎(chǔ)類向字典中添加鍵和值
向字典中添加鍵和值
添加鍵和值使用 Add 方法,但很多時(shí)候,我們是不敢輕易添加的,因?yàn)?Dictionary<TKey, TValue> 不允許重復(fù),嘗試添加重復(fù)的鍵時(shí) Add 方法引發(fā) ArgumentException。
大多時(shí)候,我們都會(huì)寫成以下的樣子:
var dict = new Dictionary<int, string>();
// ...
// 情形一:不存在才添加
if (dict.ContainsKey(2) == false) dict.Add(2, "Banana");
// 情形二:不存在添加,存在則替換
if (dict.ContainsKey(3) == false) dict.Add(3, "Orange");
else dict[3] = "Orange";
其實(shí),第二種情形可以寫如下書寫
dict[3] = "Orange";
不過好多朋友都會(huì)對(duì)這種方式表示疑慮,不太確定這樣會(huì)不會(huì)出問題。
不管是上面的哪種寫法,用字典時(shí)最大的感覺就是擔(dān)心,怕出異常,因此代碼會(huì)寫的很羅嗦。
我每次用字典時(shí)都這樣,時(shí)間長了,實(shí)在是厭煩了,索性擴(kuò)展一下,用以下兩個(gè)方法來應(yīng)對(duì)上面兩種情形:
/// <summary>
/// 嘗試將鍵和值添加到字典中:如果不存在,才添加;存在,不添加也不拋導(dǎo)常
/// </summary>
public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
if (dict.ContainsKey(key) == false) dict.Add(key, value);
return dict;
}
/// <summary>
/// 將鍵和值添加或替換到字典中:如果不存在,則添加;存在,則替換
/// </summary>
public static Dictionary<TKey, TValue> AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
dict[key] = value;
return dict;
}
TryAdd 和 AddOrReplace 這兩個(gè)方法具有較強(qiáng)自我描述能力,用起來很省心,而且也簡單:
dict.TryAdd(2, "Banana");
dict.AddOrReplace(3, "Orange");
或者像 Linq 或 jQuery 一樣連起來寫:
dict.TryAdd(1, "A")
.TryAdd(2, "B")
.AddOrReplace(3, "C")
.AddOrReplace(4, "D")
.TryAdd(5, "E");
再來看另外一個(gè)問題:
獲取值
從字典中獲取值通常使用如下方式:
string v = "defaultValue";
// 方式一
if (dict.ContainsKey(3)) v = dict[3];
// 方式二
bool isSuccess = dict.TryGetValue(3, out v);
使用索引的方式獲取前一定先判斷,否則不存在時(shí)會(huì)引發(fā) KeyNotFoundException 異常。
我尤其討厭第二種方式,因?yàn)椴捎?out 要提前聲明一個(gè)變量,代碼至少要兩行,不夠簡潔。
看下 GetValue 擴(kuò)展:
/// <summary>
/// 獲取與指定的鍵相關(guān)聯(lián)的值,如果沒有則返回輸入的默認(rèn)值
/// </summary>
public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default(TValue))
{
return dict.ContainsKey(key) ? dict[key] : defaultValue;
}
使用方便:
var v1 = dict.GetValue(2); //不存在則返回 null
var v2 = dict.GetValue(2, "abc"); //不存在返回 ”abc“
一行代碼能搞定。
批量添加
List<T> 類有個(gè) AddRange 方法,可以不用 foreach 循環(huán)直接向當(dāng)前集合加入另外一個(gè)集合:
List<string> roles = new List<string>();
roles.AddRange(new[] { "role2", "role2" });
roles.AddRange(user.GetRoles());
相當(dāng)方便,可憐 Dictionary<TKey, TValue> 類沒有,幸好有擴(kuò)展方法:
/// <summary>
/// 向字典中批量添加鍵值對(duì)
/// </summary>
/// <param name="replaceExisted">如果已存在,是否替換</param>
public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
{
foreach (var item in values)
{
if (dict.ContainsKey(item.Key) == false || replaceExisted)
dict[item.Key] = item.Value;
}
return dict;
}
使用示例:
var dict1 = new Dictionary<int, int>()
.AddOrReplace(2, 2)
.AddOrReplace(3, 3);
var dict2 = new Dictionary<int, int>()
.AddOrReplace(1, 1)
.AddOrReplace(2, 1)
.AddRange(dict1, false);
相關(guān)文章
C#實(shí)現(xiàn)應(yīng)用程序的監(jiān)控與調(diào)試的示例代碼
日志記錄是軟件開發(fā)中不可或缺的功能,它能幫助開發(fā)者在應(yīng)用程序運(yùn)行時(shí)記錄重要信息,本文就來介紹一下常用日志記錄功能以及常用的日志庫,感興趣的可以了解一下2024-03-03
C# 添加、修改以及刪除Excel迷你圖表的實(shí)現(xiàn)方法
下面小編就為大家分享一篇C# 添加、修改以及刪除Excel迷你圖表的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
C#窗體讀取EXCEL并存入SQL數(shù)據(jù)庫的方法
這篇文章主要介紹了C#窗體讀取EXCEL并存入SQL數(shù)據(jù)庫的方法,實(shí)例簡述了實(shí)現(xiàn)讀取excel及寫入SQL數(shù)據(jù)庫的原理與技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-01-01
C#使用IronPython調(diào)用python代碼的實(shí)現(xiàn)示例
本文主要介紹了在C#中使用IronPython調(diào)用Python代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
C#實(shí)現(xiàn)給DataGrid單元行添加雙擊事件的方法
這篇文章主要介紹了C#實(shí)現(xiàn)給DataGrid單元行添加雙擊事件的方法,較為詳細(xì)的分析了C#給DataGrid單元添加雙擊事件的步驟及相關(guān)實(shí)現(xiàn)代碼,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
C#中將DataTable轉(zhuǎn)換成CSV文件的方法
DataTable用于在.net項(xiàng)目中,用于緩存數(shù)據(jù),DataTable表示內(nèi)存中數(shù)據(jù)的一個(gè)表,在.net項(xiàng)目中運(yùn)用C#將DataTable轉(zhuǎn)化為CSV文件,接下來通過本文給大家提供一個(gè)通用的方法,感興趣的朋友可以參考下2016-10-10

