List.Except is not working
Asked Answered
N

2

10

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();
Niemann answered 20/10, 2012 at 12:0 Comment(4)
Your mapper is probably losing references, and the type probably has no other comparer defined.Impassible
Write a compare function using IComparerer .Dudek
@Impassible you should post it as an answer :)Turtledove
How can I map anonymous type to other type properly? if that's the caseNiemann
P
28

In order to make Except method working as expected, the class AssignUserViewModel must have GetHashCode and Equals methods correctly overridden.

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

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();
Precis answered 20/10, 2012 at 12:14 Comment(1)
Edited. Slightly changed the equality comparer Equals to account for nulls.Precis
T
3

Why this happening? When you use Set Operations (Distinct, Except, Intersect, Union) Linq need to compare sequence(s) elements for equality. By default Linq uses Object.Equals and Object.GetHashCode methods to compare elements. If these methods are not overridden in your type, then base class's implementation is used, which compare objects by reference equality. Default implementation guarantees that two objects that are the same reference have the same hash code (thus considered equal). This is your case. Mapper class creates new instances of AssignUserViewModel objects, which have different references, and cannot be treated as equal (even if all field values are the same).

So, what could we do with this?

  • Override Equals and GetHashCode methods in your class. It's up to you how you will treat objects equality - all fields, or just identity. Linq will use your methods to compare elements.

  • Provide your own comparer (this is usually case when you cannot modify your object and override Equals and GetHashCode. Yes, all Linq Set Operations have two overloads - one which uses default comparer, and other, which accepts yours IEqualityComparer<T>.

  • Use anonymous types. All anonymous types already have generated methods Equals and GetHashCode, which use comparison of all properties to determine if objects are equal. In this case you don't need neither to modify your type nor to create comparer.

Thus you already have samples of first two approaches, here is last one:

var assignUsers = accountApp.GetUsersByAccountId(context.GetUserData().AccountId)
                            .Select(u => new { u.UserId, u.Name });

var assignedUsers = mailApp.GetMailAssignedByMailId(id)
                           .Select(m => new { m.UserId, m.User.Name });

var assignUsers = assignUser.Except(assignedUsers);
// do not map until here
List<AssignUserViewModel> result = 
             assignUsers.Select(Mapper.DynamicMap<AssignUserViewModel>).ToList();
Turtledove answered 20/10, 2012 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.