Is there an easy way to convert object properties to a dictionary

后端 未结 4 1191
陌清茗
陌清茗 2020-12-28 13:23

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

4条回答
  •  鱼传尺愫
    2020-12-28 14:03

    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 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 dictionary = data.GetType().GetProperties()
        .ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? "");
    

提交回复
热议问题