Linq Conditional Selection - handling 'like' in Linq
So the first request was to use
Below is the first query I created which satisfied this request.
But scope creep raised its ugly head and the requirements were changed.. Now I need to provide results for either an 'empty' textbox or any entry such as the first couple of letter with results similar to a "Like" statement - the second example shows how I changed to accommodate.
var dbRecords = (from c in context.tbl_mydata
where (c.DateRan >= startdate && c.DateRan <= enddate)
&& (string.IsNullOrEmpty(mnum) || string.Compare(c.MNumber, mnum, true) == 0)
&& (string.IsNullOrEmpty(concept) || string.Compare(c.Concept, concept, true) == 0)
&& (!z || c.MNumber.Length <= 5)
&& (!z || c.MNumber.ToUpper().Substring(0, 1) != "T")
select new
{
c.ID,
c.DateRan,
c.FieldName
}).ToList();
THE REVISED STATEMENT
var dbRecords = (from c in context.tbl_mydata
where (c.DateRan >= startdate && c.DateRan <= enddate)
&& (string.IsNullOrEmpty(mnum) || string.Compare(c.MNumber, mnum, true) == 0)
&& (string.IsNullOrEmpty(concept) || string.Compare(c.Concept, concept, true) == 0)
&& (!z || c.MNumber.Length <= 5)
&& (!z || c.MNumber.ToUpper().Substring(0, 1) != "T")
select new
{
c.ID,
c.DateRan,
c.FieldName
}).Where(c => c.MNumber.Contains(mnum)).ToList();
- two date fields
- one optional dropdown value
- an optional textbox value
Below is the first query I created which satisfied this request.
But scope creep raised its ugly head and the requirements were changed.. Now I need to provide results for either an 'empty' textbox or any entry such as the first couple of letter with results similar to a "Like" statement - the second example shows how I changed to accommodate.
var dbRecords = (from c in context.tbl_mydata
where (c.DateRan >= startdate && c.DateRan <= enddate)
&& (string.IsNullOrEmpty(mnum) || string.Compare(c.MNumber, mnum, true) == 0)
&& (string.IsNullOrEmpty(concept) || string.Compare(c.Concept, concept, true) == 0)
&& (!z || c.MNumber.Length <= 5)
&& (!z || c.MNumber.ToUpper().Substring(0, 1) != "T")
select new
{
c.ID,
c.DateRan,
c.FieldName
}).ToList();
THE REVISED STATEMENT
This now allows for an empty mnum value which is the textbox put into a variable and an additional WHERE added to the list to filter the results if there was text supplied in the textbox.
var dbRecords = (from c in context.tbl_mydata
where (c.DateRan >= startdate && c.DateRan <= enddate)
&& (string.IsNullOrEmpty(concept) || string.Compare(c.Concept, concept, true) == 0)
&& (!z || c.MNumber.Length <= 5)
&& (!z || c.MNumber.ToUpper().Substring(0, 1) != "T")
select new
{
c.ID,
c.DateRan,
c.FieldName
}).Where(c => c.MNumber.Contains(mnum)).ToList();
Comments