Find-or-insert with only one lookup in c# dictionary

后端 未结 6 1946
粉色の甜心
粉色の甜心 2021-01-17 17:38

I\'m a former C++/STL programmer trying to code a fast marching algorithm using c#/.NET technology...

I\'m searching for an equivalent of STL method \"map::insert\"

6条回答
  •  一个人的身影
    2021-01-17 17:55

    Sadly, there isn't one in bcl's implementation. The closest alternative is doing two lookups, but one can have a generic extension method to make it easy, as shown here

    public static T GetOrAdd(this IDictionary dict, S key, 
                                   Func valueCreator)
    {
        T value;
        return dict.TryGetValue(key, out value) ? value : dict[key] = valueCreator();
    }
    

    But there is C5's implementation which does this out of the box. The method definition looks like this:

    public virtual bool FindOrAdd(K key, ref V value)
    {
    
    }
    

    I don't know why they don't accept a Func instead of V to defer object creation. C5 has a lot of nice similar tricks, for eg,

    public virtual bool Remove(K key, out V value)
    
    public virtual bool Update(K key, V value, out V oldvalue)
    
    public virtual bool UpdateOrAdd(K key, V value, out V oldvalue)
    

提交回复
热议问题