1

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

1 Answers1

2

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
    }
  );
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • You could simplify the GroupJoin by selecting both parts and then using a SelectMany with a DefaultIfEmpty to select the values from the new table if it didn't exist in the old table as well. – Robert McKee Mar 26 '15 at 07:31