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

后端 未结 7 2139
有刺的猬
有刺的猬 2020-12-29 09:57

I want to have a dynamic where condition.

In the following example:

var opportunites =  from opp in oppDC.Opportunities
                        


        
7条回答
  •  心在旅途
    2020-12-29 10:44

    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(.....);
    }
    

提交回复
热议问题