Welcome to the navigation

In id ut aliquip cillum commodo elit, excepteur et culpa in proident, anim mollit cupidatat ea minim officia duis non magna eiusmod nisi laborum, ad. Dolor ad voluptate in sed enim in adipisicing nisi ex mollit duis nulla pariatur, eiusmod amet, culpa occaecat esse elit, aliqua, irure dolor est exercitation

Yeah, this will be replaced... But please enjoy the search!

Mapping Dictionary to Typed object using c#

Categories Tags
There are some good frameworks that may help you mapping dictionaries and alike to typed objects but in some cases you simply want something simpler or custom for that matter. The most important thing here is to transfer our dictionary to a typed object.

Example dictionary

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Id", "1");
dictionary.Add("Name", "Trikks");
dictionary.Add("EMail", "info@example.com");

Example class

public class ExampleClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string EMail { get; set; }
}

Method

private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
{
    var t = new T();
    PropertyInfo[] properties = t.GetType().GetProperties();
 
    foreach (PropertyInfo property in properties)
    {
        if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
            continue;
 
        KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
 
        // Find which property type (int, string, double? etc) the CURRENT property is...
        Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
 
        // Fix nullables...
        Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
 
        // ...and change the type
        object newA = Convert.ChangeType(item.Value, newT);
        t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
    }
    return t;
}

Full example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("Id", "1");
            dictionary.Add("Name", "Trikks");
            dictionary.Add("EMail", "info@example.com");
 
            ExampleClass example = DictionaryToObject<ExampleClass>(dictionary);
        }
 
        private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
        {
            var t = new T();
            PropertyInfo[] properties = t.GetType().GetProperties();
 
            foreach (PropertyInfo property in properties)
            {
                if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
                    continue;
 
                KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
 
                // Find which property type (int, string, double? etc) the CURRENT property is...
                Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
 
                // Fix nullables...
                Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
 
                // ...and change the type
                object newA = Convert.ChangeType(item.Value, newT);
                t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
            }
            return t;
        }
    }
 
    public class ExampleClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string EMail { get; set; }
    }
}