0

I have two lists List<T> existingValues & List<T> newValues

foreach item in newvalues I check if it exists in existingValues(I check existence of value based on primary key value), if it does not exist i will add it to existingValues.

Now if value already exists in existingValues I want to check if any columns values are diffenrent and if they are different I would like to update them, how can I do this?

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
  }
}
user
  • 91
  • 2
  • 12
  • Can you not just set all the properties from one to the other? If they're different they'll change, if not they won't. Also, you should probably use a dictionary instead of any, it would be much faster. – Dispersia Feb 27 '17 at 18:21
  • Use `intersect` method: http://stackoverflow.com/questions/5065593/find-the-intersection-of-two-lists-in-linq – Mhd Feb 27 '17 at 18:22
  • @Mhd if he's going that route, you probably want to use `Except` since he wants to change the values that are different. – Dispersia Feb 27 '17 at 18:23
  • @PeterDuniho this isn't a duplicate of that question in the slightest... – Dispersia Feb 27 '17 at 19:16

2 Answers2

0

I think your code is correct except that you have to do the update before the insert.

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);
  }
}
Mhd
  • 2,778
  • 5
  • 22
  • 59
-1

I think that using a dictionary will help you (using the PrimaryKeyVal as key and them get the value and change it like in the examples below)

see -

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

How to update database using dictionary with linq

Community
  • 1
  • 1
TeaHoney
  • 150
  • 11