There is the following class:

public class MyClass { public string StrProp1 {get; set;} public string StrProp2 {get; set;} public int IntProp {get; set;} public DateTime? DTNullableProp {get; set;} public int? IntNullableProp {get; set;} } 

How to get a collection, for example Dictionary<string, string> with pairs "property name" -> "value". Values ​​are accordingly cast to the string type.

    1 answer 1

    Try this:

     o.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(o)?.ToString()); 

    For C # 5, which is not ?. , a slightly less syntactically beautiful code will do:

     o.GetType().GetProperties().ToDictionary( p => p.Name, p => { var v = p.GetValue(o); return v == null ? null : v.ToString(); } ); 

    Check: http://ideone.com/heZl2W