我曾是一名 C++/STL 程序员,尝试使用 C#/.NET 技术编写快速行进算法...
我正在寻找 STL 方法 map::insert
的等效方法,如果不存在则在给定键处插入一个值,否则返回一个指向现有键值对的迭代器。
我发现的唯一方法是通过两次查找:一次在 TryGetValue
中,另一个在 Add
方法中:
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 容器无法做到这一点?还是我错过了一些要点?
最佳答案
您可以通过以下方式分配您的值:
var dict = new Dictionary<int, int>();
dict[2] = 11;
如果键为 2 的值不存在 - 它将被添加,否则将被覆盖。
Dictionary 没有方法 GetOrAdd,但 C# 4.0 中的 ConcurrentDictionary 有:
var dict = new ConcurrentDictionary<int, int>();
dict[2] = 10;
int a = dict.GetOrAdd(2, 11);// a == 10
关于c# - 在 C# 字典中仅通过一次查找查找或插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6408916/