Conditional Linq value and a beautiful solution

Having little to no experience with Linq this one was rather tough. .  I googled Conditional Data Entity but found nothing as slick as this solution a friend sent me.

So the problem was this ... I had some textboxes, date fields etc for report filters but the textbox was OPTIONAL.  I wanted to manage the condition in the query.  

So here is what we came up with:


var dbRecords = (from c in context.myTable

where (string.IsNullOrEmpty(bnum) || string.Compare(c.BNumber, bnum, true) == 0)
 && (c.DateRan >= startdate && c.DateRan <= enddate)

And the way this works  - if bnum has a value then we will select where c.BNumber = bnum otherwise we don't use it in the where statement at all.  Really made life easy!

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax