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

后端 未结 7 2141
有刺的猬
有刺的猬 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:54

    You can dynamically add a where clause to your IQueryable expression like this:

    var finalQuery = opportunities.Where( x => x.Title == title );
    

    and for the date similarly.

    However, you will have to wait to create your anonymous type until after you've finished dynamically added your where clauses if your anonymous type doesn't contain the fields you want to query for in your where clause.

    So you might have something that looks like this:

    var opportunities =  from opp in oppDC.Opportunities
                        join org in oppDC.Organizations on 
                        opp.OrganizationID equals org.OrgnizationID
                        select opp                            
    
    if(!String.IsNullOrEmpty(title))
    {
       opportunities = opportunities.Where(opp => opp.Title == title);
    }
    
    //do the same thing for the date
    
    opportunities = from opp in opportunities
                    select new
                            {
                                opp.OpportunityID,
                                opp.Title,
                                opp.PostedBy,
                                opp.Address1,
                                opp.CreatedDate,
                                org.OrganizationName
                            };
    

提交回复
热议问题