有没有一种简单的方法可以将对象属性转换为字典<;字符串,字符串>;

本文关键字:字符串 属性 转换 字典 lt gt 对象 一种 简单 方法 有没有 | 更新日期: 2023-09-27 18:22:11

我有一个数据库对象(一行),它有很多属性(列),映射到表单字段(asp:textbox、asp:dropdownlist等)。我想将这个对象和属性转换为字典映射,以便更容易迭代。

示例:

Dictionary<string, string> FD = new Dictionary<string,string>();
FD["name"] = data.name;
FD["age"] = data.age;
FD["occupation"] = data.occupation;
FD["email"] = data.email;
..........

如果不手动键入所有不同的100个属性,我该如何轻松地做到这一点?

注意:FD字典索引和数据库列名相同。

有没有一种简单的方法可以将对象属性转换为字典<;字符串,字符串>;

假设data是某个对象,并且您希望将其公共属性放入Dictionary中,那么您可以尝试:

原创-出于历史原因(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()));

更新(2017)

Dictionary<string, string> dictionary = data.GetType().GetProperties()
    .ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? "");

HtmlHelper类允许将Anonymouns Object转换为RouteValueDictionary,我想你可以对每个值使用.ToString()来获得字符串representation:

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

不利的一面是,这是ASP.NET MVC框架的一部分。使用.NET反射器,方法内部的代码如下:

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;
 }

你会看到这个代码与叶海亚给你的答案相同,他的答案提供了一个Dictionary<字符串,字符串>。有了我给你的反射代码,你可以很容易地将RouteValueDictionary转换为Dictionary<字符串,字符串>但叶海亚的回答只是一句话。

EDIT-我已经添加了一种可以进行转换的方法的代码:

EDIT 2-我在代码中添加了null检查,并使用字符串值的String.Format

    public static Dictionary<string, string> ObjectToDictionary(object value)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        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;
    }

从字典到对象检查http://automapper.org/这是在这个线程中建议的将字典转换为匿名对象

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

public static class MyExtensions
{
    public static Dictionary<string, object> 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);
    }
}

看看System.ComponentModel.TypeDescriptor.GetProperties( ... )。这是正常数据绑定位的工作方式。它将使用反射并返回一组属性描述符(您可以使用这些描述符来获取值)。您可以通过实现ICustomTypeDescriptor来自定义这些性能描述符。