Skip to main content
 首页 » 编程设计

c#之使用 lambda 表达式更新 linq 中的多个列

2024年08月12日39mate10pro

我想使用 Linq 和 Lambda Expression 更新 DataTable 中的记录。我可以如下更新一列

dtProduct.AsEnumerable().Where(i => i.Field<long>("ProductId") == Convert.ToInt64(id)).First().SetField("Qty", qty); 

无法理解如何更新其他人:(。我最终为每一列写了好几次更新。

请您参考如下方法:

I ended up with writing update several times for each column.

您的代码由两部分组成:

  • 找到实例,并
  • 设置它的字段。

可以通过引入变量来重用定位实例的结果:

var inst = dtProduct.AsEnumerable().Where(i => i.Field<long>("ProductId") == Convert.ToInt64(id)).First(); 

现在您可以对其多次调用 SetField:

inst.SetField("Qty", qty); 
inst.SetField("Price", price); 
inst.SetField("Weight", weight);