Search code examples
c#linqlinq-to-sql

How do I implement a dynamic 'where' clause in LINQ?


I want to have a dynamic where condition.

In the following example:

var opportunites =  from opp in oppDC.Opportunities
                    join org in oppDC.Organizations 
                        on opp.OrganizationID equals org.OrgnizationID
                    where opp.Title.StartsWith(title)
                    select new
                    {
                        opp.OpportunityID,
                        opp.Title,
                        opp.PostedBy,
                        opp.Address1,
                        opp.CreatedDate,
                        org.OrganizationName
                    };

Some times I have Title and sometimes I don't. And also I want to add date in where clause dynamically.

For example, like this SQL:

string whereClause;
string SQL = whereClause == string.Empty ? 
     "Select * from someTable" : "Select * from someTable" + whereclause

Solution

  • You can rewrite it like this:

     var opportunites =  from opp in oppDC.Opportunities
                                join org in oppDC.Organizations on opp.OrganizationID equals org.OrgnizationID
                                select new
                                {
                                    opp.OpportunityID,
                                    opp.Title,
                                    opp.PostedBy,
                                    opp.Address1,
                                    opp.CreatedDate,
                                    org.OrganizationName
                                };
    
    if(condition)
    {
       opportunites  = opportunites.Where(opp => opp.Title.StartsWith(title));
    }
    

    EDIT: To answer your question in the comments, yes, you can keep appending to the original Queryable. Remember, this is all lazily executed, so at this point all it's doing it building up the IQueryable so you can keep chaining them together as needed:

    if(!String.IsNullOrEmpty(title))
    {
       opportunites  = opportunites.Where(.....);
    }
    
    if(!String.IsNullOrEmpty(name))
    {
       opportunites  = opportunites.Where(.....);
    }