【问题标题】:Update data in list if it already exits [duplicate]如果列表中的数据已经存在,则更新它[重复]
【发布时间】:2017-02-27 18:19:09
【问题描述】:

我有两个列表 List<T> existingValuesList<T> newValues

newvalues 中的 foreach 项目我检查它是否存在于existingValues 中(我根据主键值检查值是否存在),如果它不存在,我会将它添加到existingValues

现在如果 existingValues 中已经存在值,我想检查是否有任何列值不同,如果它们不同,我想更新它们,我该怎么做?

foreach(var item in newvalues)
{
  if(!existingValues.Any(x => x.PrimaryKeyVal == item.PrimaryKeyVal))
  {
   newValues.Add(item);
  }

  if (existingValues.Any(x => x.PrimaryKeyVal == item.PrimaryKeyVal))
  {
    //do something here to check if both rows are same, if not update the row with new values
  }
}

【问题讨论】:

  • 你不能只将所有属性从一个设置到另一个吗?如果他们不同,他们会改变,如果不是,他们不会。此外,您可能应该使用字典而不是任何字典,它会快得多。
  • 使用intersect方法:stackoverflow.com/questions/5065593/…
  • @Mhd 如果他要走那条路,您可能想使用Except,因为他想更改不同的值。
  • @PeterDuniho 这根本不是那个问题的重复......

标签: c# linq


【解决方案1】:

我认为您的代码是正确的,只是您必须在插入之前进行更新。

foreach(var item in newvalues)
{
  var existingItem = existingValues.Where(x => x.PrimaryKeyVal == item.PrimaryKeyVal).FirstOrDefault();
  if (existingItem != null && (x.Prop1 != item.Prop1 || x.Prop2 != item.Prop2 )))
  {
    //do something here to check if both rows are same, if not update the row with new values
    existingItem .Prop1 != item.Prop1; 
    existingItem .Prop2 != item.Prop2;

  }
  else if(existingItem == null)
  {
    newValues.Add(item);
  }
}

【讨论】:

    【解决方案2】:

    我认为使用字典会对您有所帮助(使用 PrimaryKeyVal 作为键,然后他们获取值并像下面的示例中那样更改它)

    见-

    How to update value of a key in dictionary in c#?

    How to update database using dictionary with linq

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多