如果密鑰不存在,字典返回默認值[重複] - Dictionary returning a default value if the key does not exist [duplicate]

問題:

I find myself using the current pattern quite often in my code nowadays 我發現自己現在經常在我的代碼中使用當前模式

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

var somethingElse = dictionary.ContainsKey(key) ? dictionary[key] : new List<othertype>();
// Do work with the somethingelse variable

Or sometimes 或者有時候

var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary

IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
    somethingElse = new List<othertype>();
}

Both of these ways feel quite roundabout. 這兩種方式都讓人覺得很迂迴。 What I really would like is something like 我真正想要的是這樣的

dictionary.GetValueOrDefault(key)

Now, I could write an extension method for the dictionary class that does this for me, but I figured that I might be missing something that already exists. 現在,我可以爲字典類編寫一個擴展方法來爲我做這個,但我想我可能會遺漏已經存在的東西。 SO, is there a way to do this in a way that is more "easy on the eyes" without writing an extension method to dictionary? 那麼,有沒有辦法以更簡單的方式做到這一點,而無需在字典中編寫擴展方法?


解決方案:

參考一: https://en.stackoom.com/question/AulJ
參考二: https://stackoom.com/question/AulJ
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章