c# map dictionary to object properties

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

3.5
10

                                    using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace WebOpsApi.Shared.Helpers
{
    public static class MappingExtension
    {
        public static T ToObject&lt;T&gt;(this IDictionary&lt;string, object&gt; source)
            where T : class, new()
        {
            var someObject = new T();
            var someObjectType = someObject.GetType();

            foreach (var item in source)
            {
                var key = char.ToUpper(item.Key[0]) + item.Key.Substring(1);
                var targetProperty = someObjectType.GetProperty(key);


                if (targetProperty.PropertyType == typeof (string))
                {
                    targetProperty.SetValue(someObject, item.Value);
                }
                else
                {

                    var parseMethod = targetProperty.PropertyType.GetMethod(&quot;TryParse&quot;,
                        BindingFlags.Public | BindingFlags.Static, null,
                        new[] {typeof (string), targetProperty.PropertyType.MakeByRefType()}, null);

                    if (parseMethod != null)
                    {
                        var parameters = new[] { item.Value, null };
                        var success = (bool)parseMethod.Invoke(null, parameters);
                        if (success)
                        {
                            targetProperty.SetValue(someObject, parameters[1]);
                        }

                    }
                }
            }

            return someObject;
        }

        public static IDictionary&lt;string, object&gt; AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
        {
            return source.GetType().GetProperties(bindingAttr).ToDictionary
            (
                propInfo =&gt; propInfo.Name,
                propInfo =&gt; propInfo.GetValue(source, null)
            );
        }
    }
}

3.5 (10 Votes)
0
3.7
10
B_archer 100 points

                                            class ObjectToMapTo
        {
            public int ID;
            public string Name;
            public bool IsAdmin;

            public override string ToString()
            {
                return $&quot;(ID={ID} Name={Name} IsAdmin={IsAdmin})&quot;;
            }

        }


        static object MapDictToObj(Dictionary&lt;string, object&gt; dict, Type destObject)
        {

            object returnobj = Activator.CreateInstance(destObject);

            foreach (string key in dict.Keys)
            {
                object value = dict[key];

                FieldInfo field = destObject.GetField(key);
                if (field != null)
                {
                    field.SetValue(returnobj, value);
                }


            }

            return returnobj;
        }



        static void Main(string[] args)
        {
            Dictionary&lt;string, object&gt; dict = new Dictionary&lt;string, object&gt;();
            dict[&quot;ID&quot;] = 1000;
            dict[&quot;Name&quot;] = &quot;This is a name&quot;;
            dict[&quot;IsAdmin&quot;] = true;

            ObjectToMapTo obj = (ObjectToMapTo)MapDictToObj(dict, typeof(ObjectToMapTo));

            Console.WriteLine(obj);

            Console.ReadKey();
            //Returns: (ID=1000 Name=This is a name IsAdmin=True)

        }

3.7 (10 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source