Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Contains method for a object

Tags:

c#

linq

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?

like image 329
BrunoLM Avatar asked Jul 20 '10 19:07

BrunoLM


People also ask

How do I know if IEnumerable has an item?

IEnumerable. Any() will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.

Is Linq case sensitive?

LINQ StartsWith , EndsWith , and Contains are case sensitive and return false if two same string s are of different cases, e.g., " STRING " and " string ".

What is the LINQ equivalent to the SQL IN operator?

Perform the equivalent of an SQL IN with IEnumerable. Contains().

What is Linq in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


2 Answers

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
like image 167
Reed Copsey Avatar answered Sep 27 '22 20:09

Reed Copsey


list.Any(u => u.ID == thing)
like image 35
Brian Genisio Avatar answered Sep 27 '22 19:09

Brian Genisio