.NET Dictionary: get or create new

后端 未结 8 1760
感情败类
感情败类 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 14:04

    I am missing the GetOrAdd for Dictionary, that does exist for ConcurrentDictionary.

    ConcurrentDictionary Conversion = new ConcurrentDictionary();
    List before = new List { 1, 2, 1, 3 };
    List after = before.Select(x => Conversion.GetOrAdd(x, Guid.NewGuid())).ToList();
    

    This code will generate Guids for each number. Ending up converting both 1's in before to the same Guid.

    In your case:

    ConcurrentDictionary> dict;
    keyValues = dict.GetOrAdd(key, new List());
    keyValues.Add(aValueForKey);
    

提交回复
热议问题