[英]Easy way to convert a Dictionary<string, string> to xml and vice versa
[英]Is there an easy way to convert object properties to a dictionary<string, string>
我有一个数据库对象(一行),它有许多映射到表单字段的属性(列) (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对象转换为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 <string,string>。 通过我给你的反映代码,你可以轻松地将RouteValueDictionary转换为Dictonary <string,string>,但是Yahia的答案是一个单行。
编辑 - 我添加了可用于转换的方法的代码:
编辑2 - 我已经对代码添加了空检查,并使用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
定义这些描述符以进行性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.