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 开发者_JAVA百科Contains?
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>
.
var check = list.Where(lu => lu.ID == users[0].ID)
and then test forcheck.Count() == 1
var check = list.FirstOrDefault(lu => lu.ID == users[0].ID)
and then test forcheck != null
.list.Any(user => user.ID == users[1].ID);
精彩评论