.NET Dictionary: get or create new

后端 未结 8 1745
感情败类
感情败类 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条回答
  •  Happy的楠姐
    2020-12-08 13:56

    Here is a solution in case the constructor requires a parameter.

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

    Simple to use:

    MyDict.GetOrCreate(si.Id, createNew: () => new ObjectKnowingItsId(si.Id))
    

提交回复
热议问题