本文介绍了List.Except 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我尝试减去 2 个列表,如下面的代码,assignUsers 有 3 条记录,assignedUsers 有 2 行.在 Except 方法之后,我仍然得到 3 行,虽然我应该得到 1 条记录,因为 assignedUsers 中的 2 行类似于 assignUsers I try to subtract 2 lists like below code, assignUsers has got 3 records and assignedUsers has got 2 rows. After Except method I still get 3 rows, although I should get 1 record because 2 rows in assignedUsers is similar to assignUsers var users = accountApp.GetUsersByAccountId(context.GetUserData().AccountId); List<AssignUserViewModel> assignUsers = Mapper.Map<List<AssignUserViewModel>>(users).ToList(); var mailUsers = mailApp.GetMailAssignedByMailId(id).Select(m => new { m.UserId, m.User.Name }).ToList(); List<AssignUserViewModel> assignedUsers = mailUsers.Select(Mapper.DynamicMap<AssignUserViewModel>).ToList(); assignUsers = assignUsers.Except(assignedUsers).ToList();推荐答案为了使 Except 方法按预期工作,AssignUserViewModel 类必须具有 GetHashCode 和 Equals 方法被正确覆盖.In order to make Except method working as expected, the class AssignUserViewModel must have GetHashCode and Equals methods correctly overridden.例如,如果 AssignUserViewModel 对象是由它们的 Id 唯一定义的,你应该这样定义类:For example, if AssignUserViewModel objects are uniquely defined by their Id, you should define the class in this way:class AssignUserViewModel{ // other methods... public override int GetHashCode() { return this.Id.GetHashCode(); } public override bool Equals(object obj) { if (!(obj is AssignUserViewModel)) throw new ArgumentException("obj is not an AssignUserViewModel"); var usr = obj as AssignUserViewModel; if (usr == null) return false; return this.Id.Equals(usr.Id); }}否则,如果你不能/不想改变类的实现,你可以实现一个 IEqualityComparer 并将它传递给 Except 方法,例如:Otherwise, if you can't/don't want to change the class implementation, you can implement an IEqualityComparer<> and pass it to the Except method, e.g. :class AssignUserViewModelEqualityComparer : IEqualityComparer<AssignUserViewModel>{ public bool Equals(AssignUserViewModel x, AssignUserViewModel y) { if (object.ReferenceEquals(x, y)) return true; if(x == null || y == null) return false; return x.Id.Equals(y.Id); } public int GetHashCode(AssignUserViewModel obj) { return obj.Id.GetHashCode(); }}那么你的最后一行将变成:then your last line would become:assignUsers = assignUsers.Except(assignedUsers, new AssignUserViewModelEqualityComparer()).ToList(); 这篇关于List.Except 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-24 17:40