Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Update a List from Another List

Tags:

c#

I have 2 List<object>. The first one, lets call it ListA is more like a complete list and the second one ListB is a modified list. Now what I want to do is to modify ListA with ListB. Is this doable and how can I do it. This is what I have so far but doesn't work:

var ListB = _repository.Get(m => m.Approved == true).ToList();
foreach (var x in ListB)
{
  ListA.Where(d => d.Name == x.Name).First() = x;
}

return ListA;

EDIT: Visual Presentation to describe what 'modify' means in my situation

ListA
Id     Name      Age
1     John       14
2     Mark       15
3     Luke       13
4     Matthew    18

ListB
Id     Name      Age
2     Mark       0
4     Matthew    99

After 'modifying' it, ListA should look like:

ListA
Id     Name      Age
1     John       14
2     Mark       0
3     Luke       13
4     Matthew    99
like image 951
super-user Avatar asked Apr 10 '16 12:04

super-user


2 Answers

As I consider, you want to update only an age. Also you don't need to use Where().First() you can use just First().

foreach (var x in ListB)
{
    var itemToChange = ListA.First(d => d.Name == x.Name).Age = x.Age;
}

If you are not sure, that item exists in ListA you should use FirstOrDefault() and if statement to check it.

foreach (var x in ListB)
{
    var itemToChange = ListA.FirstOrDefault(d => d.Name == x.Name);
    if (itemToChange != null)
         itemToChange.Age = x.Age;
}
like image 151
Valentin Avatar answered Oct 10 '22 10:10

Valentin


Where and First return IEnumerable - you can modify only node of the list, but not reassign.

option 0 - generic approach

using System.Collections.Generic;

//...

   var itemToUpdate = ListA.FirstOrDefault(d => d.Name == x.Name);
   if (itemToUpdate != null) {
       ListA[ListA.IndexOf(itemToUpdate)] = x;
   }

option 1 - implement the update method or perform field update manually

ListA.First(d => d.Name == x.Name).Update(x);
like image 33
Andrey Ershov Avatar answered Oct 10 '22 10:10

Andrey Ershov