更改对象的多个字段值

Change multiple field values of an object

我有一个对象集合(比如产品),我想更改集合中每个对象的一些字段值。我想定义字段名称和它对应的值如下

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

对于每个预先填充的产品对象的名称和类别字段值,都需要用 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; }
}

您可以使用 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));
    }

}