Linq Contains method for a object

You need to check a User, not an int. Enumerable.Any will work well for this:

// this does work
list.Any(user => user.ID == users[0].ID);         // false
list.Any(user => user.ID == users[1].ID);         // true !
list.Any(user => user.ID == users[2].ID);         // false

list.Any(u => u.ID == thing)

If you want to avoid the lambda expression, and think you may need to compare User objects by ID in other parts of your code, consider writing a comparer as follows.

class UserEqualityComparer : IEqualityComparer<User>
{
    bool IEqualityComparer<User>.Equals(User lhs, User rhs)
    {
        return lhs.ID == rhs.ID;
    }

    int IEqualityComparer<User>.GetHashCode(User user)
    {
        return user.ID;  // assumes all IDs are unique.
    }
}

Then your list query looks like the following.

IEnumerable<User> list = GetList();
IEqualityComparer<User> userComparer = new UserEqualityComparer();

list.Contains(users[0], userComparer);
list.Contains(users[1], userComparer);
// etc...

To answer your question related to speed of retrieval, Contains is the fastest way if you don't know how the User objects are ordered in your collection. If they were sorted by ID and stored in a List<User> object, you could use the List<User>.BinarySearch() method with an appropriate implementation of IComparer<User>.

Tags:

C#

Linq