Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to convert object properties to a dictionary<string, string>

I have a database object (a row), that has lots of properties (columns) that map to form fields (asp:textbox, asp:dropdownlist etc). I would like to transform this object and properties into a dictionary map to make it easier to iterate.

Example:

Dictionary<string, string> FD = new Dictionary<string,string>(); FD["name"] = data.name; FD["age"] = data.age; FD["occupation"] = data.occupation; FD["email"] = data.email; .......... 

How would I do this easily, without manually typing out all the various 100s of properties?

Note: FD dictionary indices are same as database column names.

like image 922
Dexter Avatar asked Feb 02 '12 15:02

Dexter


People also ask

How do you turn an object into a dictionary?

I found it easy to json serialize the object and deserialize as a dictionary. var json = JsonConvert. SerializeObject(obj); var dictionary = JsonConvert. DeserializeObject<Dictionary<string, string>>(json);

How do you turn an object into a string?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Can we convert list to dictionary in C#?

Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.


1 Answers

Assuming that data is some object and that you want to put its public properties into a Dictionary then you could try:

Original - here for historical reasons (2012):

Dictionary<string, string> FD = (from x in data.GetType().GetProperties() select x)     .ToDictionary (x => x.Name, x => (x.GetGetMethod().Invoke (data, null) == null ? "" : x.GetGetMethod().Invoke (data, null).ToString())); 

Updated (2017):

Dictionary<string, string> dictionary = data.GetType().GetProperties()     .ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? ""); 
like image 90
Yahia Avatar answered Oct 08 '22 11:10

Yahia