How can I convert a class into Dictionary<string,string>?
This is the recipe: 1 reflection, 1 LINQ-to-Objects!
someObject.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => (string)prop.GetValue(someObject, null))
Since I published this answer I've checked that many people found it useful. I invite everyone looking for this simple solution to check another Q&A where I generalized it into an extension method: Mapping object to dictionary and vice versa
Here a example with reflection without LINQ:
Location local = new Location();
local.city = "Lisbon";
local.country = "Portugal";
local.state = "None";
PropertyInfo[] infos = local.GetType().GetProperties();
Dictionary<string,string> dix = new Dictionary<string,string> ();
foreach (PropertyInfo info in infos)
{
dix.Add(info.Name, info.GetValue(local, null).ToString());
}
foreach (string key in dix.Keys)
{
Console.WriteLine("nameProperty: {0}; value: {1}", key, dix[key]);
}
Console.Read();
I would like to add an alternative to reflection, using JToken. You will need to check the benchmark difference between the two to see which has better performance.
var location = new Location() { City = "London" };
var locationToken = JToken.FromObject(location);
var locationObject = locationObject.Value<JObject>();
var locationPropertyList = locationObject.Properties()
.Select(x => new KeyValuePair<string, string>(x.Name, x.Value.ToString()));
Note this method is best for a flat class structure.