convert object to dictionary c# code example

Example 1: c# convert dictionary to anonymous object

var dict = new Dictionary<string, object> { { "Property", "foo" } };
dynamic eo = dict.Aggregate(new ExpandoObject() as IDictionary<string, Object>,
                            (a, p) => { a.Add(p.Key, p.Value); return a; });
string value = eo.Property;

Example 2: convert dto to dictionary c#

someObject.GetType()
     .GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))

Example 3: convert dictionary to object c#

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

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

        }


        static object MapDictToObj(Dictionary<string, object> 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<string, object> dict = new Dictionary<string, object>();
            dict["ID"] = 1000;
            dict["Name"] = "This is a name";
            dict["IsAdmin"] = true;

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

            Console.WriteLine(obj);

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

        }