C# 有没有一种简单的方法可以将对象属性转换为字典<string, string>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9115413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an easy way to convert object properties to a dictionary<string, string>
提问by Dexter
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 object and properties into a dictionary map to make it easier to iterate.
我有一个数据库对象(一行),它有很多属性(列)映射到表单字段(asp:textbox、asp:dropdownlist 等)。我想将此对象和属性转换为字典映射以使其更易于迭代。
Example:
例子:
Dictionary<string, string> FD = new Dictionary<string,string>();
FD["name"] = data.name;
FD["age"] = data.age;
FD["occupation"] = data.occupation;
FD["email"] = data.email;
..........
How would I do this easily, without manually typing out all the various 100s of properties?
我如何轻松地做到这一点,而无需手动输入所有 100 多个属性?
Note: FD dictionary indices are same as database column names.
注意:FD 字典索引与数据库列名相同。
采纳答案by Yahia
Assuming that datais some object and that you want to put its public properties into a Dictionary then you could try:
假设这data是某个对象,并且您想将其公共属性放入 Dictionary 中,那么您可以尝试:
Original - here for historical reasons (2012):
原版 - 出于历史原因(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()));
Updated (2017):
更新(2017):
Dictionary<string, string> dictionary = data.GetType().GetProperties()
.ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? "");
回答by Nick Bork
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:
HtmlHelper 类允许将匿名对象转换为 RouteValueDictonary,我想您可以在每个值上使用 .ToString() 来获取字符串表示:
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:
缺点是这是 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;
}
You'll see that this code is identical to the answer Yahia gave you, and his answer provides a Dictonary<string,string>. With the reflected code I gave you you could easily convert a RouteValueDictionary to Dictonary<string,string> but Yahia's answer is a one liner.
您会看到此代码与 Yahia 给您的答案相同,并且他的答案提供了 Dictonary<string,string>。使用我给您的反射代码,您可以轻松地将 RouteValueDictionary 转换为 Dictonary<string,string> 但 Yahia 的答案是单行。
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
编辑 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;
}
And to go from a Dictionary to an object check http://automapper.org/which was suggested in this thread Convert dictionary to anonymous object
并从字典到对象检查http://automapper.org/在此线程中建议 将字典转换为匿名对象
回答by L.B
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);
}
}
回答by MaLio
Take a look at System.ComponentModel.TypeDescriptor.GetProperties( ... ). This is the way the normal data binding bits work. It will use reflection and return you a collection of property descriptors (which you can use to get the values). You can customize these descriptors for performace by implementing ICustomTypeDescriptor.
看看System.ComponentModel.TypeDescriptor.GetProperties( ... )。这是正常数据绑定位的工作方式。它将使用反射并返回一组属性描述符(您可以使用它来获取值)。您可以通过实现ICustomTypeDescriptor.

