Search code examples
sqllinq-to-entities

fastest way to check if linq query returns results


I do not need to know the actual results or even a count - just if the result is null or not.

I am currently doing it like this and then looking at the count:

int itemsNeedingUpdated = 
    (from i in cDb.DistributionLineItems
     where (i.CompanyNo == item.dt_company_no && i.UniqueIdNo == item.Unique_Id_No) &&
            (i.DatetimeUpdated >= startingDateTimeToSearch) &&
            (i.ReceivingScanPieces > 0 || i.LoadingScanPieces > 0 || i.ActualPieces > 0)
     select i.UniqueIdNo).Count();

but as this is going to churn through a lot of times I want to know if this is the fastest way to check this?

Using EF 6 against Azure SQL.


Solution

  • You can use Any:

    bool itemsNeedingUpdated = 
        (from i in cDb.DistributionLineItems
         where (i.CompanyNo == item.dt_company_no && i.UniqueIdNo == item.Unique_Id_No) &&
               (i.DatetimeUpdated >= startingDateTimeToSearch) &&
               (i.ReceivingScanPieces > 0 || i.LoadingScanPieces > 0 || i.ActualPieces > 0)
         select i.UniqueIdNo).
         Any();
    

    Which will bail out as soon as an item matching the predicate is found.