.NET Dictionary: get or create new

后端 未结 8 1744
感情败类
感情败类 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:53

    If you use .Net Core you can use Dictionary<>.TryAdd().

    var dict = new Dictionary();
    dict.TryAdd("foo", "bar"); // returns bool whether it added or not feel free to ignore.
    var myValue = dict["foo"];
    

提交回复
热议问题