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.
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);
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.
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
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() ?? "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With