将类中的值存储/恢复到属性名称和值列表中

时间:2011-04-06 15:32:09

标签: c# linq collections

我不确定最好和最简单的方法是什么,所以任何建议都值得赞赏。

我希望获取任何/所有/单个域实体类的所有字段,并在调用特定方法时动态添加前缀/删除前缀。

例如,我有以下实体:

public class Shop
{
 public string TypeOfShop{get;set}
 public string OwnerName {get;set}
 public string Address {get;set}
}

public class Garage
{
 public string Company {get;set}
 public string Name {get;set}
 public string Address {get;set}
}

依旧......

我想获得一个带有前缀的属性列表:

public Class Simple
{
    public class Prop
    {
     public string Name{get;set;}
     public string Value{get;set;}
    } 

    public ICollection list = new List<Prop>();

    //set all prop
    public void GetPropertiesWithPrefix(Garage mygarage, string prefix)
    {
     list.Add(new Prop{Name = prefix + "_Company", Value = mygarage.Company});
     //so on... upto 50 props...
    }

}

//to get this list I can simple call the list property on the Simple class

当我读取每个字段时,我使用的是switch语句并设置值。

//Note I return a collection of Prop that have new values set within the view,lets say
//this is a result returned from a controller with the existing prop names and new values...

public MyGarage SetValuesForGarage(MyGarage mygarage, string prefix, ICollection<Prop> _props)
{

  foreach (var item in _prop)
  {
   switch(item.Name)
   {
     case prefix + "Company":
     mygarage.Company = item.Value;
     break;
     //so on for each property...

   }

  }

}

使用linq或其他方式有更好,更简单或更优雅的方法吗?

2 个答案:

答案 0 :(得分:0)

也许以下方法适合您。它接受任何对象,查找其属性并返回包含Prop对象的列表,每个属性对应每个属性。

public class PropertyReader
{
    public static List<Prop> GetPropertiesWithPrefix(object obj, string prefix)
    {
        if (obj == null)
        {
            return new List<Prop>();
        }

        var allProps = from propInfo
                       in obj.GetType().GetProperties()
                       select new Prop()
                       {
                           Name = prefix + propInfo.Name,
                           Value = propInfo.GetValue(obj, null) as string
                       };
        return allProps.ToList();
    }
}

答案 1 :(得分:0)

您可以将道具存储在字典中,然后:

mygarage.Company = _props[prefix + "_Company"];
mygarage.Address = _props[prefix + "_Address"];
//And so on...

在您的SetValuesForGarage方法中,而不是内部带有switch的循环。

修改

有关使用Dictionary的详细信息,请参阅MSDN

您可以定义list之类的内容:

Dictionary<string, string> list = new Dictionary<string, string>();

GetPropertiesWithPrefix方法中使用以下内容:

list.Add(prefix + "_Company", mygarage.Company);
list.Add(prefix + "_Address", mygarage.Address);
//And so on...

这会消除您的Prop课程。