且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 LINQ 中实现动态“where"子句?

更新时间:2023-10-23 15:55:16

你可以这样重写:

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

要在评论中回答您的问题,是的,您可以继续附加到原始 Queryable.请记住,这一切都是惰性执行的,因此此时它正在构建 IQueryable,以便您可以根据需要继续将它们链接在一起:

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