相关疑难解决方法(0)

如果键不存在,则字典返回默认值

我发现自己现在经常在我的代码中使用当前模式

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)

现在,我可以为字典类编写一个扩展方法来为我做这个,但我想我可能会遗漏已经存在的东西.那么,有没有办法以更简单的方式做到这一点,而无需在字典中编写扩展方法?

c# collections dictionary

216
推荐指数
4
解决办法
14万
查看次数

是否有一个IDictionary实现,在缺少键时,返回默认值而不是抛出?

如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?

我知道"TryGetValue"方法,但这不可能与linq一起使用.

这会有效地做我需要的吗?:

myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)

我认为它不会,因为我认为它将迭代键而不是使用哈希查找.

.net c# hash dictionary

116
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×2

dictionary ×2

.net ×1

collections ×1

hash ×1