Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if results from LINQ query contains a value

Tags:

c#

asp.net

linq

I have a LINQ query that brings back all records from a table called Permissions, where the userId is the current user.

What I want to do is run a check on this result set and see if PermissionId of value 5 exists..

Whats the easiest way to do this?

like image 366
Matt Avatar asked Apr 18 '11 01:04

Matt


1 Answers

bool contains_id_5; 
contains_id_5 = Permissions.Where(p=>p.PermissionID==5).Count() > 0;
contains_id_5 = Permissions.Where(p=>p.PermissionID==5).Any();
contains_id_5 = Permissions.Where(p=>p.PermissionID==5).FirstOrDefault() != null;
contains_id_5 = Permissions.Any(p=>p.PermissionID==5);

Which one you use depends on whether you have any use for the intermediate bits (the count, the record) or not. Permissions.Any(p=>p.PermissionID==5) can be the most efficient with Queryable type LINQ collections, especially as part of a larger query, since it can turn into a SQL EXISTS call if you're not using any of the other bits.

like image 133
Random832 Avatar answered Sep 27 '22 23:09

Random832