Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...