在C#中使用Linq Lambda更新多个记录 [英] Updating Multiple records using Linq Lambda in C#
本文介绍了在C#中使用Linq Lambda更新多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ThresholdTable
表,其中有两列ID varchar(max)
和Value varchar(max)
I have a ThresholdTable
table with two columns ID varchar(max)
and Value varchar(max)
ID | Value
----------------
1 | 0701224225
2 | 0701224012
我想将其更新为
ID | Value
----------------
1 | 105394
2 | 105595
如何通过C#,Linq,Lambda表达式实现.
How I can achieve through C#, Linq, Lambda expression.
我正在这样做,
private const string ThresholdValue1 = "1";
private const string ThresholdValue2 = "2";
var Setting = this.context.ThresholdTable.Where(p => p.ID.Equals(ThresholdValue1) || p.ID.Equals(ThresholdValue2));
foreach (var s in Setting)
{
if (s.ID.Equals(ThresholdValue1))
{
s.Value = "105394";
}
else if (s.ID.Equals(ThresholdValue2))
{
s.Value = 105595;
}
this.context.SaveChanges();
}
请给我建议一些更好的方法.
Please suggest me some better way.
推荐答案
Linq
用于查询数据,而不用于更新数据.
Linq
is for querying data, not for updating them.
现在,为了更好地替代代码,如果要更新的值很多,可以将所需的值放在Dictionary
中,并在循环遍历它们的同时更新值,例如
Now, for a better alternative of your code, if you many values to update, you can put your desired values in a Dictionary
and update your values while looping through them like
var valuesToPopulate = new Dictionary<string, string> {
{ "1", "105394" },
{ "2", "105595" }
};
foreach (var threashold in this.context.ThresholdTable)
{
var valueToPopulate = valuesToPopulate.FirstOrDefault(d => d.Key.Equals(threashold.ID.Equals));
if (!valueToPopulate.Equals(new KeyValuePair<string, string>()))
threashold.Value = valueToPopulate.Value;
}
this.context.SaveChanges();
这篇关于在C#中使用Linq Lambda更新多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文