tags:

views:

47

answers:

4

I have a object User and it is the following class:

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

And I have a IEnumerable<User>

I want to find out if one specific user exists in IEnumerable<User>, comparing the user by it's ID.

An example:

IList<User> users = GetUsers();     // 1, 2, 3
IEnumerable<User> list = GetList(); // 2, 5, 8

// this doesn't work
list.Contains(users[0].ID);         // false
list.Contains(users[1].ID);         // true !
list.Contains(users[2].ID);         // false

How can I do it? And what is the fastest way to retrieve this boolean, is it Contains?

+6  A: 

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
Reed Copsey
+3  A: 
list.Any(u => u.ID == thing)
Brian Genisio
A: 
  1. var check = list.Where(lu => lu.ID == users[0].ID) and then test for check.Count() == 1
  2. var check = list.FirstOrDefault(lu => lu.ID == users[0].ID) and then test for check != null.
  3. list.Any(user => user.ID == users[1].ID);
Femaref
+1  A: 

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.Equals(User lhs, User rhs)
    {
        return lhs.ID == rhs.ID;
    }

    int IEqualityComparer.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>.

Steve Guidi