C# LINQ code for two list compare and replace

☆樱花仙子☆ 提交于 2021-02-10 23:52:37

问题


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:


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
    }
  );


来源:https://stackoverflow.com/questions/29272315/c-sharp-linq-code-for-two-list-compare-and-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!