簡體   English   中英

有沒有一種簡單的方法可以將對象屬性轉換為字典<string, string>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM