tma*_*ino 0 c# dictionary trygetvalue
我一直在使用TryGetValue在我的词典中添加/替换数据.为了区分添加new和替换旧,我同时使用[]和.Add().这导致像这样的代码,如果我实际上没有对检索到的值做任何事情:
private Dictionary<Foo, Bar> dictionary = new Dictionary<Foo, Bar>();
public void Update(Foo foo)
{
Bar bar;
if (dictionary.TryGetValue(foo, out bar)
{
dictionary [foo] = bar;
}
else
{
dictionary .Add(foo, bar);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我实际上没有对检索到的值做任何事情,是否有理由不用这个代替上面的代码?:
public void Update(Foo foo)
{
dictionary[foo] = bar;
}
Run Code Online (Sandbox Code Playgroud)
先感谢您.
您应该使用更简单的代码.
在所有情况下都会更快.(一个哈希查找与两个)
更重要的是,它更简单.
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |