{"id":622,"date":"2019-12-18T22:09:58","date_gmt":"2019-12-18T21:09:58","guid":{"rendered":"https:\/\/thomasjansen.eu\/?p=622"},"modified":"2019-12-18T22:31:30","modified_gmt":"2019-12-18T21:31:30","slug":"trygetvalueorcreate","status":"publish","type":"post","link":"https:\/\/thomas-jansen.eu\/?p=622","title":{"rendered":"TryGetValueOrCreate"},"content":{"rendered":"\n<p>Get an existing item from a dictionary or create a new value with a default value, using an extension method.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> static class extensionMethods\n {\n\n     public static V TryGetValueOrCreate&lt;K, V>(this Dictionary&lt;K, V> dictionary, K key) \n     where V : new()\n    {\n       V data;\n       if (!dictionary.TryGetValue(key, out data))\n       {\n          data = new V();\n          dictionary.Add(key, data);\n       }\n       return (data);\n    }\n }<\/code><\/pre>\n\n\n\n<p>The method above can be used using the code below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Item\n{\n   public int test;\n};\n\nDictionary&lt;int,Item> dict = new Dictionary&lt;int,Item>();\nItem item = dict.TryGetValueOrCreate(3);\nitem.test= 123;\n\n<\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Get an existing item from a dictionary or create a new value with a default value, using an extension method. The method above can be used using the code below:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-622","post","type-post","status-publish","format-standard","hentry","category-c"],"_links":{"self":[{"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/posts\/622","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=622"}],"version-history":[{"count":2,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/posts\/622\/revisions"}],"predecessor-version":[{"id":624,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=\/wp\/v2\/posts\/622\/revisions\/624"}],"wp:attachment":[{"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=622"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=622"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thomas-jansen.eu\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=622"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}