使用linq合并2个列表,其中至少有一个属性已更改

时间:2014-08-26 13:02:05

标签: c# linq

var usersOld = new List<User>();
var userOld1 = new User { IsDisabled = true, IsLicenced = false, Id = 1 };
var userOld2 = new User { IsDisabled = true, IsLicenced = false, Id = 2 };
var userOld3 = new User { IsDisabled = true, IsLicenced = false, Id = 3 };
var userOld4 = new User { IsDisabled = true, IsLicenced = false, Id = 4 };

usersOld.Add(userOld1);
usersOld.Add(userOld2);
usersOld.Add(userOld3);
usersOld.Add(userOld4);

var usersToday = new List<User>();
var userNew1 = new User { IsDisabled = true, IsLicenced = true, Id = 1 };
var userNew2 = new User { IsDisabled = true, IsLicenced = false, Id = 2 };
var userNew3 = new User { IsDisabled = false, IsLicenced = false, Id = 3 };
var userNew4 = new User { IsDisabled = true, IsLicenced = true, Id = 4 };

usersToday.Add(userNew1);
usersToday.Add(userNew2);
usersToday.Add(userNew3);
usersToday.Add(userNew4);

var query = null; 

如何将两个列表合并到一个列表中,其中至少有一个属性hasChanged,因此用户是&#34;脏&#34;

//根据我的逻辑,id为1,3和4的用户在两个属性中都发生了变化。在现实生活中注意可以和将来         //比这两个属性更多的属性。

1 个答案:

答案 0 :(得分:2)

正如Mephy所说,实施IEquatable<User>会使这更简单 - 此时,您可以只执行连接:

var changes = usersOld.Join(usersNew, o => o.Id, n => n.Id,
                            (o, n) => new { Old = o, New = n })
                      .Where(pair => !pair.Old.Equals(pair.New));

然后,无论何时添加相关属性,您只需更改Equals实施以考虑到这一点。

结果是一系列对 - 目前作为匿名类型,但如果您想从方法返回,则可以使用Tuple<,>