[ACCEPTED]-Check if results from LINQ query contains a value-linq
Accepted answer
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 6 have any use for the intermediate bits (the 5 count, the record) or not. Permissions.Any(p=>p.PermissionID==5)
can be the most 4 efficient with Queryable type LINQ collections, especially 3 as part of a larger query, since it can 2 turn into a SQL EXISTS
call if you're not using 1 any of the other bits.
var PermissionIDFiveCount=YourInitialDataset.Where(p=>p.PermissionID==5).Count()
Or shorter way:
var PermissionIDFiveCount=YourInitialDataset.Count(p=>p.PermissionID==5)
Even shorter:
var ContainsPermissionIDFive=YourInitialDataset.Any(p=>p.PermissionID==5)
0
If you're returning an IQueryable, just 2 query the results for what you want.
var results = repository.GetAllPermissions(id);
var result2 = from r in results where r.PermissionID == 5 select r;
bool contains5 = result2.Count() > 0;
Or you 1 could do something like this:
var contains5 = repository.GetAllPermissions(id).Count(c => c.PermissionID == 5) > 0;
More advanced way can be just by modifying 1 Random832's code as follows.
bool contains_id_5;
contains_id_5 = Permissions.Count(p=>p.PermissionID==5) > 0;
contains_id_5 = Permissions.Any(p=>p.PermissionID==5);
contains_id_5 = Permissions.FirstOrDefault(p=>p.PermissionID==5) != null;
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.