Tip #212: Getting a yes or no answer in LINQ

Say, you need to find out if your organization has any opportunities with the estimated value of more than a million dollars (that’s right, that’s how developers usually roll). No need to retrieve anything, just simple yes or no. There are many ways to accomplish the task, most of them, sadly, are as efficient as shaving yak with a disposable razor.

Chances are some people will write this:

var opportunities = crm.OpportunitySet
    .Where(opp => opp.EstimatedValue >= 1000000m);
if(opportunities.FirstOrDefault() == null) 
{
    // we have a winner
}

or even this

var opportunities = crm.OpportunitySet
    .Where(opp => opp.EstimatedValue >= 1000000m)
    .ToList();                
if(opportunities.Count > 0) 
{
    // we have a winner
}

LINQ parser quite often is smart and forgiving and you may get away with the first one but why take any chances and drag records across the wire? (second snippet is really bad, in case you missed that)

This code will get you home:

if(crm.OpportunitySet
    .Any(opp => opp.EstimatedValue >= 1000000m))
{
    // we have a winner
}

Even without looking at the final results I would bet that the last snippet would use EXISTS clause in T-SQL which is the most efficient way to check for record existence.

One thought on “Tip #212: Getting a yes or no answer in LINQ

  1. Daniel K. says:

    Thanks for the tip. I started development with LINQ in the last days.

    By the way: We use our CRM system for selling big steel plants. So the million dollar opp is not unusual here.

Leave a Reply

Your email address will not be published. Required fields are marked *