在c#字典中只进行一次查找的查找或插入操作 [英] Find-or-insert with only one lookup in c# dictionary
问题描述
我是一个以前的C ++ / STL程序员,试图使用c#/。NET技术编写一个快速前进算法...
I'm a former C++/STL programmer trying to code a fast marching algorithm using c#/.NET technology...
如果不存在,在给定键处插入一个值的STL方法map :: insert,否则返回现有键值对的迭代器。
I'm searching for an equivalent of STL method "map::insert" that insert a value at given key if not exists, else returns an iterator to the existing key-value pair.
我发现这有两个查找:一个在TryGetValue和另一个在添加方法:
The only way I found does this with two lookups : one inside TryGetValue and another one in Add method :
List<Point> list;
if (!_dictionary.TryGetValue (pcost, out list))
{
list = new List<Point> ();
dictionary.Add (pcost, list);
}
list.Add (new Point { X = n.x, Y = n.y });
有什么解释为什么这是不可能使用.NET容器?
Is there something that explains why this is not possible using .NET containers ? Or did I missed some point ?
感谢。
推荐答案
可以按照以下方式分配值:
You can just assign your value in the following way:
var dict = new Dictionary<int, int>();
dict[2] = 11;
如果键2的值不存在 - 将被添加,否则它将被覆盖。
if value with key 2 does not exist - it will be added and otherwise it will be just overriden.
字典没有GetOrAdd方法,但来自C#4.0的ConcurrentDictionary会执行:
Dictionary does not have method GetOrAdd, but ConcurrentDictionary from C# 4.0 does:
var dict = new ConcurrentDictionary<int, int>();
dict[2] = 10;
int a = dict.GetOrAdd(2, 11);// a == 10
这篇关于在c#字典中只进行一次查找的查找或插入操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!