c# - 如果键不存在,字典返回默认值

标签 c# collections dictionary

<分区>

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

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

或者有时

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

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

这两种方式感觉都很迂回。我真正想要的是

dictionary.GetValueOrDefault(key)

现在,我可以为字典类编写一个扩展方法来为我做这件事,但我认为我可能遗漏了一些已经存在的东西。那么,有没有一种方法可以在不为字典编写扩展方法的情况下以更“容易理解”的方式来做到这一点?

最佳答案

TryGetValue 已经将类型的默认值分配给字典,因此您可以使用:

dictionary.TryGetValue(key, out value);

并忽略返回值。然而,实际上只返回default(TValue),而不是一些自定义默认值(也不是更有用的执行委托(delegate)的结果)。框架中没有比这更强大的了。我会建议两种扩展方法:

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key,
    TValue defaultValue)
{
    return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key,
    Func<TValue> defaultValueProvider)
{
    return dictionary.TryGetValue(key, out var value) ? value : defaultValueProvider();
}

(当然,您可能想要检查参数:)

关于c# - 如果键不存在,字典返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601477/

相关文章:

c# - 使用 LINQ 从 List 或 foreach 循环中获取行是否更快

c# - SortedSet<T> 与 HashSet<T>

Python;使用字典查找数字代码的因子。为什么这不起作用?

python - 在字典的python字典中搜索

c# - 在实现中设置私有(private) Setter 的模拟 void 方法

c# - ASP.Net LinkBut​​ton 在本地工作但不能在服务器上工作

javascript - 我怎样才能更好地写出这份报告候选人的功能呢?

仅针对添加(插入)操作优化的 Java 集合

pandas - 如何使用词典中的词典?

c# 检查 Windows 帐户是否在特定域中被锁定