C# Linq syntax help – How to exclude two values

clinqlinq-to-sql

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

Best Answer

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.