Linq and how to redefine them correctly

Why var excludes = users.Except(matches);not excluded matches?

What is the correct way if I want the comparator to be equal to use only ID? Examples would be appreciated.

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return ID.ToString() + ":" + Name;
    }
}

private static void LinqTest2()
{
    IEnumerable<User> users = new List<User>
    {
        new User {ID = 1, Name = "Jack"},
        new User {ID = 2, Name = "Tom"},
        new User {ID = 3, Name = "Jim"},
        new User {ID = 4, Name = "Joe"},
        new User {ID = 5, Name = "James"},
        new User {ID = 6, Name = "Matt"},
        new User {ID = 7, Name = "Jon"},
        new User {ID = 8, Name = "Jill"}
    }.OfType<User>();

    IEnumerable<User> localList = new List<User>
    {
        new User {ID = 4, Name = "Joe"},
        new User {ID = 5, Name = "James"}
    }.OfType<User>();


    //After creating the two list
    var matches = from u in users
                  join lu in localList
                    on u.ID equals lu.ID
                  select lu;
    Console.WriteLine("--------------MATCHES----------------");
    foreach (var item in matches)
    {
        Console.WriteLine(item.ToString());
    }

    Console.WriteLine("--------------EXCLUDES----------------");
    var excludes = users.Except(matches);
    foreach (var item in excludes)
    {
        Console.WriteLine(item.ToString());
    }            
}
+3
source share
2 answers
    sealed class CompareUsersById : IEqualityComparer<User>
    {
        public bool Equals(User x, User y)
        {
            if(x == null)
                return y == null;
            else if(y == null)
                return false;
            else
                return x.ID == y.ID;
        }

        public int GetHashCode(User obj)
        {
            return obj.ID;
        }
    }

and then

var excludes = users.Except(matches, new CompareUsersById());
+7
source

The user class does not override Equalsand GetHashCode, therefore, the Equalsdefault implementation is used . In this case, it means that it compares the links. You have created two user objects with the same values, but since they differ from each other, they are compared with unequal ones.

Equals , IEqualityComparer.

+3

Source: https://habr.com/ru/post/1768776/


All Articles