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?
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.
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 ".
Perform the equivalent of an SQL IN with IEnumerable. Contains().
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With