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

后端 未结 4 1182
陌清茗
陌清茗 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:10

    var myDict = myObj.ToDictionary(); //returns all public fields & properties
    

    .

    public static class MyExtensions
    {
        public static Dictionary ToDictionary(this object myObj)
        {
            return myObj.GetType()
                .GetProperties()
                .Select(pi => new { Name = pi.Name, Value = pi.GetValue(myObj, null) })
                .Union( 
                    myObj.GetType()
                    .GetFields()
                    .Select(fi => new { Name = fi.Name, Value = fi.GetValue(myObj) })
                 )
                .ToDictionary(ks => ks.Name, vs => vs.Value);
        }
    }
    

提交回复
热议问题