C # compare two lists one by one Property and change the value of the first list

I have the following problem: I have two lists of type foo. Now I want to go through both lists, since in the second list I changed the values ​​of two properties. To clarify what I mean here, the code I know will work:

foreach(foo bar in list_1) {
  foreach(foo bar2 in list_2) {
    if (bar.ID == bar2.ID) {
      bar.name = bar2.name;
      bar.color = bar2.color;
    }
  }
}

So, as you can see, the properties in list_2 have different values, like in list_1, but I also need them in list_1. This will work like this, but I wonder if there will be an easier way to do this (maybe with LinQ?)

Regards, Asat0r

+4
source share
1 answer

ID list_2, ( )

  // A little bit of Linq: ToDictionary 
  var dict = list_2.ToDictionary(item => item.ID, item => item);
  ...
  foreach (item in list_1) {
    foo master;

    if (dict.TryGetValue(item.ID, out master)) {
      item.name = master.name; 
      item.color = master.color;
    }
  }
+1

All Articles