问题描述
我尝试减去以下代码中的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不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!