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

Wah*_*eed 12 c# linq linq-to-sql

我希望有一个动态的where条件.

在以下示例中:

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
                    };
Run Code Online (Sandbox Code Playgroud)

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

例如,像这样的SQL:

string whereClause;
string SQL = whereClause == string.Empty ? 
     "Select * from someTable" : "Select * from someTable" + whereclause
Run Code Online (Sandbox Code Playgroud)

BFr*_*ree 22

你可以像这样重写它:

 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));
}
Run Code Online (Sandbox Code Playgroud)

编辑:要在评论中回答您的问题,是的,您可以继续附加到原始的可查询.记住,这都是懒惰的执行,所以在这一点上,所有它都在构建IQueryable,这样你就可以根据需要将它们链接在一起:

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

if(!String.IsNullOrEmpty(name))
{
   opportunites  = opportunites.Where(.....);
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 5

您可以动态地将where子句添加到IQueryable表达式,如下所示:

var finalQuery = opportunities.Where( x => x.Title == title );
Run Code Online (Sandbox Code Playgroud)

同样的日期.

但是,如果匿名类型不包含要在where子句中查询的字段,则必须等到创建匿名类型,直到完成动态添加where子句为止.

所以你可能会看到这样的东西:

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
                        };
Run Code Online (Sandbox Code Playgroud)