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?
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.
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