C# LINQ code for two list compare and replace

I have two list of object 'User',

    User u1 = new User { Id = 1, Name = "user1" };
    User u2 = new User { Id = 2, Name = "user2" };
    User u3 = new User { Id = 3, Name = "user3" };
    User u3_1 = new User { Id = 10, Name = "user3" };
    User u5 = new User { Id = 5, Name = "user5" };
    User u6 = new User { Id = 6, Name = "user6" };

    List<User> listOld = new List<User> { u1, u2, u3 };
    List<User> listNew = new List<User> { u1, u2, u3_1, u5, u6 };

u3 and u3_1 is two objects which have same Name and different ID

I want to compare 'listOld' and 'listNew' by object's 'Name' property and get the Old object value to the 'listNew'.

final result should be

listNew = {u1, u2, u3, u5, u6}

if I say simply, compare the two list using list items's 'Name' and get the old object to the new list

I just want to know the LINQ code for this.

Thank you

Upvotes: 1

Views: 478

Answers (1)

Robert McKee
Robert McKee

Reputation: 21487

Probably not the most efficient way, but this should work:

var result=listNew
  .GroupJoin(listOld,k1=>k1.Name,k2=>k2.Name,(k1,k2)=>
    new User {
      Id=k2.SingleOrDefault()==null?k1.Id:k2.SingleOrDefault().Id,
      Name=k2.SingleOrDefault()==null?k1.Name:k2.SingleOrDefault().Name
    }
  );

Upvotes: 2

Related Questions