Welcome to the navigation

Et mollit dolore pariatur, dolor nulla eiusmod commodo consequat, minim lorem in aliquip tempor incididunt id consectetur excepteur in officia sint occaecat sed laboris proident. Sit laborum, tempor excepteur ex dolor amet, exercitation quis reprehenderit eu incididunt duis culpa ad qui ut irure veniam, consectetur nostrud aliquip aute cillum mollit

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; }
    }
}