Welcome to the navigation

Aliquip aliqua, dolor magna ut sed occaecat in ad mollit exercitation et consequat, sit incididunt sint ea do anim laborum, eiusmod culpa eu duis fugiat. Voluptate dolore quis reprehenderit laborum, id aliqua, cupidatat duis dolore adipisicing officia et nulla occaecat veniam, minim aute dolor ullamco magna enim deserunt ex nisi

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; }
    }
}
Please note that this portal is a BETA site , I will continuously improve all functionality and performance during the coming weeks / the author