{"id":4018,"date":"2020-09-08T09:52:44","date_gmt":"2020-09-08T08:52:44","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=4018"},"modified":"2022-07-25T08:32:07","modified_gmt":"2022-07-25T07:32:07","slug":"c-object-to-dictionary","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-object-to-dictionary\/","title":{"rendered":"C# object to dictionary"},"content":{"rendered":"\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static class ObjectToDictionaryHelper\n{\n\tpublic static IDictionary&lt;string, T> ToDictionary&lt;T>(object source)\n\t{\n\t\tif (source == null)\n\t\t\tthrow new ArgumentNullException(\"source\", \"Cannot convert null to a dictionary.\");\n\n\t\tvar dictionary = new Dictionary&lt;string, T>();\n\t\tforeach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))\n\t\t\tAddPropertyToDictionary&lt;T>(property, source, dictionary);\n\t\treturn dictionary;\n\t}\n\n\tprivate static void AddPropertyToDictionary&lt;T>(PropertyDescriptor property, object source, Dictionary&lt;string, T> dictionary)\n\t{\n\t\tobject value = property.GetValue(source);\n\t\tif (value is T)\n\t\t\tdictionary.Add(property.Name, (T)value);\n\t}\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-4018","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/4018","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=4018"}],"version-history":[{"count":3,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/4018\/revisions"}],"predecessor-version":[{"id":4021,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/4018\/revisions\/4021"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=4018"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=4018"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=4018"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}