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

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

    The HtmlHelper class allows a conversion of Anonymouns Object to RouteValueDictonary and I suppose you could use a .ToString() on each value to get the string repersentation:

     var linkAttributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(linkHtmlAttributes);
    

    The down side is this is part of the ASP.NET MVC Framework. Using a .NET Reflector, the code inside of the method is as follows:

    public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes)
    {
       RouteValueDictionary dictionary = new RouteValueDictionary();
      if (htmlAttributes != null)
      {
         foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(htmlAttributes))
         {
                dictionary.Add(descriptor.Name.Replace('_', '-'), descriptor.GetValue(htmlAttributes));
           }
     }
        return dictionary;
     }
    

    You'll see that this code is identical to the answer Yahia gave you, and his answer provides a Dictonary. With the reflected code I gave you you could easily convert a RouteValueDictionary to Dictonary but Yahia's answer is a one liner.

    EDIT - I've added the code for what could be a method to do your conversion:

    EDIT 2 - I've added null checking to the code and used String.Format for the string value

        public static Dictionary ObjectToDictionary(object value)
        {
            Dictionary dictionary = new Dictionary();
            if (value != null)
            {
                foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(value))
                {
                    if(descriptor != null && descriptor.Name != null)
                    {
                         object propValue = descriptor.GetValue(value);
                         if(propValue != null)
                              dictionary.Add(descriptor.Name,String.Format("{0}",propValue));
                }
            }
            return dictionary;
        }
    

    And to go from a Dictionary to an object check http://automapper.org/ which was suggested in this thread Convert dictionary to anonymous object

提交回复
热议问题