I have 2 List
. 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 i
You could also use the Union method with an 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();
}
}
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;
}
to elaborate aershov's 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 nulls and everything.
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);
You could remove all elements of ListB
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();