Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL Where Clause Optional Criteria

I am working with a LINQ to SQL query and have run into an issue where I have 4 optional fields to filter the data result on. By optional, I mean has the choice to enter a value or not. Specifically, a few text boxes that could have a value or have an empty string and a few drop down lists that could have had a value selected or maybe not...

For example:

    using (TagsModelDataContext db = new TagsModelDataContext())      {         var query = from tags in db.TagsHeaders                     where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())                      && Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE                     && Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE                     select tags;         this.Results = query.ToADOTable(rec => new object[] { query });     } 

Now I need to add the following fields/filters, but only if they are supplied by the user.

  1. Product Number - Comes from another table that can be joined to TagsHeaders.
  2. PO Number - a field within the TagsHeaders table.
  3. Order Number - Similar to PO #, just different column.
  4. Product Status - If the user selected this from a drop down, need to apply selected value here.

The query I already have is working great, but to complete the function, need to be able to add these 4 other items in the where clause, just don't know how!

like image 956
RSolberg Avatar asked Mar 10 '09 21:03

RSolberg


People also ask

How to use LINQ where clause with multiple conditions?

LINQ Where Clause with Multiple Conditions. In LINQ we can use Where() clause in the query to define multiple conditions like as shown below C# Code

How to use where clause filtering operator in LINQ?

Let's see example of using where clause filtering operator in LINQ. Following is the example of using LINQ where clause filtering operator with method syntax to filter records based on where condition. IEnumerable<string> result = countries.Where (x => x.StartsWith ("A"));

What are the where conditions in LINQ and Lambda queries?

We have specified two where conditions in both linq and lambda queries. The first where clause checks for the income that is greater than 25,000 and the second where clause looks for the income that is less than 45,000. We can see there is just one income between 25000 and 40000. So we should be getting this as output from both queries.

Is there a LINQ equivalent of a complex SQL query?

Check out this thread, as it might give you some nice pointers: C# LINQ equivalent of a somewhat complex SQL query


Video Answer


1 Answers

You can code your original query:

var query = from tags in db.TagsHeaders                 where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper())                  && Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE                 && Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE                 select tags; 

And then based on a condition, add additional where constraints.

if(condition)     query = query.Where(i => i.PONumber == "ABC");  

I am not sure how to code this with the query syntax but id does work with a lambda. Also works with query syntax for the initial query and a lambda for the secondary filter.

You can also include an extension method (below) that I coded up a while back to include conditional where statements. (Doesn't work well with the query syntax):

        var query = db.TagsHeaders             .Where(tags => tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()))             .Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE)             .Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE)             .WhereIf(condition1, tags => tags.PONumber == "ABC")             .WhereIf(condition2, tags => tags.XYZ > 123); 

The extension method:

public static IQueryable<TSource> WhereIf<TSource>(     this IQueryable<TSource> source, bool condition,     Expression<Func<TSource, bool>> predicate) {     if (condition)         return source.Where(predicate);     else         return source; } 

Here is the same extension method for IEnumerables:

public static IEnumerable<TSource> WhereIf<TSource>(     this IEnumerable<TSource> source, bool condition,     Func<TSource, bool> predicate) {     if (condition)         return source.Where(predicate);     else         return source; } 
like image 131
andleer Avatar answered Oct 09 '22 17:10

andleer