Convert Dictionary To Anonymous Object in C#
To convert dictionary to an object we can use< code>ExpandoObject which represents an object whose members can be dynamically added and removed at run time, this class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember
instead of more complex syntax like sampleObject.GetAttribute("sampleMember")
.Remember to include all required namespaces:
using System;
, using System.Collections.Generic;
, using System.Dynamic;
.Example
using System;
using System.Collections.Generic;
using System.Dynamic;
public class Example
{
public class Location
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
}
public static void Main()
{
var dict = new Dictionary<string, object>
{ { "city", "Detroit" }, {"state", "Michigan"}, {"country", "USA"} };
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;
foreach (var kvp in dict)
{
eoColl.Add(kvp);
}
dynamic eoDynamic = eo;
Console.WriteLine(eoDynamic.city);
}
}
Output
Detroit