C # Refresh list from another list

I have 2 List<object> . The first, lets call it ListA is more like a complete list, and the second ListB is a modified list. Now I want to change ListA using ListB. Is it doable and how can I do it. This is what I have so far but not working:

 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: A visual presentation to describe what “change” 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 the “modification”, ListA should look like this:

 ListA Id Name Age 1 John 14 2 Mark 0 3 Luke 13 4 Matthew 99 
+7
c #
source share
5 answers

In my opinion, you want to update only age. Also you do not need to use Where().First() , you can only use First() .

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

If you are not sure if this element exists in ListA , you should use FirstOrDefault() and the 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; } 
+6
source share

Where is the first IEnumerable return - you can change only the node of the list, but not reassign it.

option 0 - general 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 update method or perform manual update manually

 ListA.First(d => d.Name == x.Name).Update(x); 
+4
source share

work out the Aershov answer:

 ListA.Where(d => d.Name == x.Name).First().CopyFrom(x); 

then in your Person class:

 public class Person { // ... Name, Id, Age properties... public void CopyFrom(Person p) { this.Name = p.Name; this.Id = p.Id; this.Age = p.Age; } } 

Of course, check zeros and that’s it.

+3
source share

You can remove all ListB items from ListA based on Id , add ListB to ListA , and then sort using Id .

 var newlist = ListA.Where(s => !ListB.Any(p => p.Id == s.Id)).ToList(); newlist.AddRange(ListB); ListA = newlist.OrderBy(o => o.Id).ToList(); 
+2
source share

You can also use the Union method with IEqualityComparer:

 var newList = ListB.Union(ListA, new PersonEqualityComparer()); class PersonEqualityComparer : IEqualityComparer<Person> { public bool Equals(Person person1, Person person2) { if (person1 == null && person2 == null) return true; else if ((person1 != null && person2 == null) || (person1 == null && person2 != null)) return false; return person1.Id.Equals(person2.Id); } public int GetHashCode(Person item) { return item.Id.GetHashCode(); } } 
0
source share

All Articles