我发现自己现在经常在我的代码中使用当前模式
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
Run Code Online (Sandbox Code Playgroud)
或者有时候
var dictionary = new Dictionary<type, IList<othertype>>();
// Add stuff to dictionary
IList<othertype> somethingElse;
if(!dictionary.TryGetValue(key, out somethingElse) {
somethingElse = new List<othertype>();
}
Run Code Online (Sandbox Code Playgroud)
这两种方式都让人觉得很迂回.我真正想要的是这样的
dictionary.GetValueOrDefault(key)
Run Code Online (Sandbox Code Playgroud)
现在,我可以为字典类编写一个扩展方法来为我做这个,但我想我可能会遗漏已经存在的东西.那么,有没有办法以更简单的方式做到这一点,而无需在字典中编写扩展方法?
如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?
我知道"TryGetValue"方法,但这不可能与linq一起使用.
这会有效地做我需要的吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)
我认为它不会,因为我认为它将迭代键而不是使用哈希查找.