Chintan Chintan - 1 year ago 56
ASP.NET (C#) Question

How to convert class into Dictionary<string,string>?

Now again I am explaining one of my eagerness about Dictionary ! This question is popuped in my mind from answer of my previous question !!

Now the actual point is Can I convert Class into Dictionary ?

In Dictionary I want my class properties as KEY and value of particular property as VALUE

Suppose my class is

public class Location
public string city { get; set; }
public string state { get; set; }
public string country { get; set;

Now suppose my data is

city = Delhi
state = Delhi
country = India

Now you can understand my point easily !

I want to make Dictionary ! That dictionary should be like

Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");

I can get the value ! But how can i get property names (not value)?

What should I code to create it dynamic ! That should work for every class which I want ?

You can understand this question as

How can i get list of properties from particular class ?

Answer Source

This is the recipe: 1 reflection, 1 LINQ-to-Objects!

     .GetProperties(BindingFlags.Instance | BindingFlags.Public)
          .ToDictionary(prop => prop.Name, prop => 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download