更改对象的多个字段值

时间:2015-08-03 00:25:40

标签: c# linq reflection

我有一个对象集合(比如Products),我想更改集合中每个对象的一些字段值。我想定义字段名称及其对应的值,如下所示

var mapData = new Dictionary<string,string>();
mapData.Add("Name","N");
mapData.Add("Category", "C");

对于每个预先填充的Product对象的Name和Category字段,需要使用N和C覆盖值。我试图使用LINQ执行此操作,并且卡住了。

    [StepArgumentTransformation]
    public IEnumerable<Product> TransformProductData(Table table)
    {
        var mapData = new Dictionary<string,string>();
        mapData.Add("Name","N");
        mapData.Add("Category", "C");

        foreach(var product in table.CreateSet<Product>)
        {
          var transformedProduct = typeof(product).GetProperties().Select
                    (
                        prop => mapData.First(x => x.Key.Equals(prop.Name))
                        // How do I assign the change the values here ??
                    )
        }

    }

假设产品对象如下所示

    public class Product
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public string Amount { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Linq将属性(来自Product类型)与mapData中的值相关联。定义关联后,只需根据属性和关联值设置每个产品的值即可。

这样的事情:

[StepArgumentTransformation]
public IEnumerable<Product> TransformProductData(Table table)
{
    var mapData = new Dictionary<string,string>();
    mapData.Add("Name","N");
    mapData.Add("Category", "C");

    var prodProcessors = typeof(Product).GetProperties()
      .Where(prop => mapData.ContainsKey(prop.Name))
      .Select(prop => new { Property = prop, Value = mapData[prop.Name]})
      .ToList();

    foreach(var product in table.CreateSet<Product>)
    {
      prodProcessors.ForEach(x => x.Property.SetValue(product, x.Value));
    }

}