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

发布于 2025-01-02 15:05:32 字数 393 浏览 0 评论 0原文

我有一个数据库对象(一行),它有许多映射到表单字段的属性(列)(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;
..........

我如何轻松地完成此操作,而无需手动输入所有数百个属性?

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

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.

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?

Note: FD dictionary indices are same as database column names.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

缱绻入梦 2025-01-09 15:05:32

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

原始 - 此处出于历史原因(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() ?? "");

Assuming that data is some object and that you want to put its public properties into a Dictionary then you could try:

Original - here for historical reasons (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):

Dictionary<string, string> dictionary = data.GetType().GetProperties()
    .ToDictionary(x => x.Name, x => x.GetValue(data)?.ToString() ?? "");
深爱成瘾 2025-01-09 15:05:32

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。使用我给您的反映代码,您可以轻松地将 RouteValueDictionary 转换为 Dictonary但叶海亚的回答是一句简单的话。

编辑 - 我添加了可能是进行转换的方法的代码:

编辑 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/在这个线程中
将字典转换为匿名对象

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:

 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:

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.

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

    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

热血少△年 2025-01-09 15:05:32
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);
    }
}
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);
    }
}
叶落知秋 2025-01-09 15:05:32

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

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 .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文