在c#字典中只有一个查找的查找或插入

eth*_*ham 10 c# lookup comparison performance stl

我是一名前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 });
Run Code Online (Sandbox Code Playgroud)

是否有一些东西可以解释为什么使用.NET容器不可能?还是我错过了一些观点?

谢谢.

Ole*_*nyk 11

您可以通过以下方式分配您的值:

var dict = new Dictionary<int, int>();
dict[2] = 11;
Run Code Online (Sandbox Code Playgroud)

如果键2的值不存在 - 它将被添加,否则它将被覆盖.

Dictionary没有方法GetOrAdd,但C#4.0的ConcurrentDictionary有:

var dict = new ConcurrentDictionary<int, int>();
dict[2] = 10;
int a = dict.GetOrAdd(2, 11);// a == 10
Run Code Online (Sandbox Code Playgroud)

  • @amichai gerstl不,请试一试 (3认同)

TcK*_*cKs -3

您可以为此创建扩展方法:

IDictionary<string, Point> _dictionary = GetDictionary();
_dictionary.GetOrAdd( "asdf" ).Add( new Point(14, 15) );

// ... elsewhere ...
public static class DictionaryExtensions {
    public static List<TValue> GetOrAdd<TKey, TValue>( this IDictionary<TKey, List<TValue>> self, TKey key ) {
        List<TValue> result;
        self.TryGetValue( key, out result );
        if ( null == result ) {
            // the key value can be set to the null
            result = new List<TValue>();
            self[key] = result;
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这与问题中的代码相同,只是现在进行了扩展。这有什么帮助?还有 2 个调用,trygetvalue 和 add。 (3认同)