用户登录
用户注册

分享至

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

  • 作者: 嗫?暁雲?
  • 来源: 51数据库
  • 2022-12-13

问题描述

我想要一个动态的 where 条件.

I want to have a dynamic where condition.

在下面的例子中:

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

有时我有Title,有时没有.而且我想在 where 子句中动态添加日期.

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

例如像这样的SQL:

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

推荐答案

你可以这样重写:

 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(.....);
}
软件
前端设计
程序设计
Java相关