您可以使用以下代码代替 foreach。
class Product
{
public int ID { get; set; }
public string Description { get; set; }
public int Price { get; set; }
}
将测试数据分配到列表
List<Product> list = new List<Product>() {
new Product() { ID = 1, Description = "BBB" , Price = 10},
new Product() { ID = 2, Description = "CCC" , Price = 40},
new Product() { ID = 3, Description = "DDD" , Price = 60}};
List<Product> newList = new List<Product>();
newList.Add(new Product() { ID = list[0].ID , Description = string.Join(", ", list.Select(a => a.Description).ToArray()),
Price = list.Select(a => a.Price).Sum()});
此外,如果您想从 ListView 中获取价值,您可以使用以下代码。
var p = new Product()
{
ID = Convert.ToInt32((ListView1.Items[0].FindControl("lblID") as Label).Text),
Description = string.Join(", ", (ListView1.Items.Select(a => (a.FindControl("lblDescription") as Label).Text)).ToArray()),
Price = ListView1.Items.Select(a => Convert.ToInt32((a.FindControl("lblPrice") as Label).Text)).Sum()
};
而且您还必须用您的标签替换“lblID”。