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
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;
}
Where and First return IEnumerable - you can modify only node of the list, but not reassign.
using System.Collections.Generic;
//...
var itemToUpdate = ListA.FirstOrDefault(d => d.Name == x.Name);
if (itemToUpdate != null) {
ListA[ListA.IndexOf(itemToUpdate)] = x;
}
ListA.First(d => d.Name == x.Name).Update(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With