简体   繁体   English

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

[英]Is there an easy way to convert object properties to a dictionary<string, string>

I have a database object (a row), that has lots of properties (columns) that map to form fields (asp:textbox, asp:dropdownlist etc) . 我有一个数据库对象(一行),它有许多映射到表单字段的属性(列) (asp:textbox,asp:dropdownlist等) I would like to transform this object and properties into a dictionary map to make it easier to iterate. 我想将此对象和属性转换为字典映射,以便更容易迭代。

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字典索引与数据库列名称相同。

Assuming that data is 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() ?? "");

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类允许将Anonymouns对象转换为RouteValueDictonary,我想你可以在每个值上使用.ToString()来获取字符串再入:

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

The down side is this is part of the ASP.NET MVC Framework. 缺点是这是ASP.NET MVC框架的一部分。 Using a .NET Reflector, the code inside of the method is as follows: 使用.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>. 您会看到此代码与Yahia给您的答案相同,并且他的答案提供了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. 通过我给你的反映代码,你可以轻松地将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/这个线程中建议将字典转换为匿名对象

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

Take a look at System.ComponentModel.TypeDescriptor.GetProperties( ... ) . 看看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 . 您可以通过实现ICustomTypeDescriptor定义这些描述符以进行性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将Dictionary <string,string>转换为xml的简便方法,反之亦然 - Easy way to convert a Dictionary<string, string> to xml and vice versa 转换字典的最简单方法是什么? <string, string> 到字典 <string, object> ? - What is the leanest way to convert a Dictionary<string, string> to a Dictionary<string, object>? 填充字典的简便方法 <string,List<string> &gt; - Easy way to Populate a Dictionary<string,List<string>> 转换字典 <object, string> 到字典 <string, string> - Convert Dictionary<object, string> to Dictionary<string, string> 有没有一种简单的方法可以将所有对象的属性获取为字符串? - Is there an easy way of getting all of an objects properties as a string? 有没有简单的方法(包装器/字典)从 Keys enum 转换为 SenKeys 字符串? - Is there any easy way (wrapper/dictionary) to convert from Keys enum to SenKeys string? 将字典对象转换为Json字符串 - Convert dictionary object into Json string 如何转换字典 <string, object> 到字典 <string, string> 在C#中 - How to convert Dictionary<string, object> to Dictionary<string, string> in c# 有没有一种方法可以序列化Dictionary <string, string> 有一个内在的对象? - Is there a way to serialize Dictionary<string, string> with an inner object? 转换字典<string, object>匿名 Object?</string,> - Convert Dictionary<string, object> To Anonymous Object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM