.NET Dictionary: get or create new

后端 未结 8 1758
感情败类
感情败类 2020-12-08 13:38

I often find myself creating a Dictionary with a non-trivial value class (e.g. List), and then always writing the same code pattern when filling in data.

For example

8条回答
  •  清歌不尽
    2020-12-08 13:51

    We have a slightly different take on this, but the effect is similar:

    public static TValue GetOrCreate(this IDictionary dict, TKey key) 
        where TValue : new()
    {
        TValue val;
    
        if (!dict.TryGetValue(key, out val))
        {
            val = new TValue();
            dict.Add(key, val);
        }
    
        return val;
    }
    

    Called:

    var dictionary = new Dictionary>();
    
    List numbers = dictionary.GetOrCreate("key");
    

    It makes use of the generic constraint for public parameterless constructors: where TValue : new().

    To help with discovery, unless the extension method is quite specific to a narrow problem, we tend to place extension methods in the namespace of the type they are extending, in this case:

    namespace System.Collections.Generic
    

    Most of the time, the person using the type has the using statement defined at the top, so IntelliSense would also find the extension methods for it defined in your code.

提交回复
热议问题