Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c# - Linq Contains method for a object

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...