views:

215

answers:

4

Hi all,

I have this linq query that works well (although it may be written better, pls say so if you notice something)

var qry = BenefitCodes
    .Where(b => b.BenInterest != 'E' 
       && (b.BenProductLine == CoverageProductLine || b.BenProductLine == null) )
    .Select(b => b)
    .OrderBy(b => b.BenDesc);

A new requirement came down the pipeline to exclude two BenCodes ( 1001, 1009), BenCodes is just another column in the SQL table.

Am I supposed to use some variation of ".Contains", I would have to do !Contains or something. Can anyone point me in the right direction?

Thanks, ~ck in San Diego

+2  A: 

You could just simply add another line to the Where clause and exclude every itm with a BenCodes of 1001 or 1009.

Like this:

var qry = BenefitCodes.Where(b => b.BenInterest != 'E' && (b.BenProductLine == CoverageProductLine || b.BenProductLine == null) && b.BenCodes != 1001 && b.BenCodes != 1009 ).Select(b => b).OrderBy(b => b.BenDesc);
Robban
+2  A: 

Yes, one way to handle this is the following (for brevity and readability, I am excluding the remainder of your query):

var excludedBenCodes = new List<int>() { 1001, 1009 };
var query = BenefitCodes.Where(b => !excludedBenCodes.Contains(b.BenCodes));

I believe this to be more readable and more maintainable than the alternative of adding a subclause b.BenCodes != 1001 && b.BenCodes != 1009 to your where clause.

Jason
I agree. The other solution works, but this is more maintainable and readable. Thanks!
Hcabnettek
A: 
var qry = BenefitCodes
    .Where(b => b.Code != '1001' 
        && b.Code != '1009' 
        && b.BenInterest != 'E' 
        && (  b.BenProductLine == CoverageProductLine 
           || b.BenProductLine == null))
    .OrderBy(b => b.BenDesc);

You don't even need the "Select" when you aren't using the LINQ syntax. as the Where and OrderBy methods already return your IQueryable.

free-dom
+1  A: 

This might make things a bit more readable, I'd change query to

var qry = BenefitCodes.Where(b => FitsCriteria(b)).OrderBy(b => b.BenDesc);

and add method

public bool FitsCriteria(BenefitCode b)
{
return b.BenInterest != 'E' && 
   (b.BenProductLine == CoverageProductLine || b.BenProductLine == null) && 
   b.BenCodes != 1001 && 
   b.BenCodes != 1009;
}

Kindness,

Dan

Daniel Elliott
Hmmm. Will factoring the criteria into a method prevent Linq to SQL from generating SQL? Also, 'Kindness'? Far too touchy feely! Let's have a bit more gruff machismo in future @agileguy.
mackenir
Grrr. Gruffy Gruff .... no the method refactor will NOT break deferred or prevent Linq to SQL doing it's thing :)
Daniel Elliott
Ah OK. Clever stuff that Expression... [shoulder punch]
mackenir