使用Linq (
我生成的代码
TrendyolProductAddlist model = new TrendyolProductAddlist
{
items = new List<ProductAdditems>
{
new ProductAdditems
{
barcode=entegrasyon_barkod,
title=urun_baslik,
productMainId=stok_kodu,
brandId=trendyol_marka_id,
categoryId=trendyol_kategori_id,
quantity=stok,
stockCode=stok_kodu,
dimensionalWeight=desi,
description=urun_aciklama,
currencyType=para_birimi,
listPrice=Convert.ToDecimal(trendyol_psf),
salePrice=Convert.ToDecimal(trendyol_price),
vatRate = urun_kdv,
cargoCompanyId=kargo_id,
images = new List<Productimagelist>
{
new Productimagelist { url = resim1 }
} ,
attributes = new List<Productattributeslist>
{
new Productattributeslist { attributeId=renk_id, customAttributeValue= renk },
new Productattributeslist { attributeId=cinsiyet_id, attributeValueId= cinsiyet_valueid },
new Productattributeslist { attributeId = yasgrubu_id, attributeValueId = yasgrubu_valueid }
}
}
}
};
类:
public string attributeId { get; set; }
public string attributeValueId { get; set; }
public string customAttributeValue { get; set; }
我怎样才能得到这样的代码?我想在dgw
中添加一个新列表attributes = new List<Productattributeslist>
{
foreach (DataGridViewRow dgwRow in dataGridView1.Row)
{
new Productattributeslist { attributeId = dgwRow.Cells[0].Value , customAttributeValue = dgwRow.Cells[1].Value },
}
}
我想在DGW中使用多少行发送属性将会发生,但它将不可能循环它是可见的
你的关注和问题似乎是支持循环控制流,因为它涉及到对象和集合初始化;语法似乎不支持内联循环(这会扩展到对象初始化器中),但是您可以通过在右赋值期间调用来实现该结果。
在您提供的代码片段中,您的目标是基于dataGridView1.Row
中DataGridViewRow
的集合生成一个初始化的List<Productattributeslist>
实例。
调用Helper函数
attributes = GenerateProductAttributesList(dataGridView1.Rows)
#region "Helper Functions" // Can be defined as private static, or local .. depends on scope and testability you have in mind
List<Productattributeslist> GenerateProductAttributesList(DataGridViewRowCollection dgwRows) {
var resultList = new List<Productattributeslist>();
foreach (DataGridViewRow dgwRow in dgwRows)
{
resultList.Add(SelectProductAttributesListItem(dgwRow));
}
return resultList;
}
Productattributeslist SelectProductAttributesListItem(DataGridViewRow dgvwRow) => new Productattributeslist()
{
attributeId = dgvwRow.Cells[0].Value,
customAttributeValue = dgvwRow.Cells[1].Value
};
#endregion
使用Linq (using System.Linq;
at top)
attributes = dataGridView1.Rows.Cast<DataGridViewRow>().Select((dgvwRow) => new Productattributeslist()
{
attributeId = dgvwRow.Cells[0].Value,
customAttributeValue = dgvwRow.Cells[1].Value
}).ToList()
上面的Linq示例使用了一个定义并传递给.Select
方法的匿名委托。这通常是用于简单映射的方法,但是您可以考虑声明一个方法来传递。
使用Linq和传递Helper函数作为委托的组合。
attributes = dataGridView1.Rows.Cast<DataGridViewRow>().Select(SelectProductAttributesListItem).ToList()
#region "Helper Function"
Productattributeslist SelectProductAttributesListItem(DataGridViewRow dgvwRow) => new Productattributeslist()
{
attributeId = dgvwRow.Cells[0].Value,
customAttributeValue = dgvwRow.Cells[1].Value
};
#endregion