有没有一种简单的方法可以将对象属性转换为字典

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

例:

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

如果不手动输入所有不同的100个属性,我怎么能这么做呢?

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

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

原创 – 这里有历史原因(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())); 

更新(2017年)

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

HtmlHelper类允许将Anonymouns对象转换为RouteValueDictonary,我想您可以对每个值使用.ToString()来获取字符串重新进行:

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

缺点是这是ASP.NET MVC框架的一部分。 使用.NET Reflector,方法内部的代码如下:

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

您将看到此代码与Yahia给您的答案相同,并且他的答案提供了Dictonary 。 通过我给你的reflection代码,你可以轻松地将RouteValueDictionary转换为Dictonary ,但Yahia的答案是一个单行。

编辑 – 我添加了可用于转换的方法的代码:

编辑2 – 我已经对代码添加了空检查,并使用String.Format作为字符串值

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

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

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

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