如何在linq查询中嵌入字符串条件

时间:2011-03-18 13:22:48

标签: asp.net-mvc linq-to-sql

我想在我的linq查询中应用几个条件。我的方案是我从表中获取记录,如果用户选择一些标准,则根据应用条件。所以我想做的是

var linq = from p in Post select p
//now if user apply that condition
string id = "1"; //Here 1 is what user inputs
string condition = where p.id == id 
//then it executes query like this 
linq = from p in Post condition select p

我可以在linq中执行此操作,如果是,那么

2 个答案:

答案 0 :(得分:4)

var linq = from p in Post select p;

//now if user apply that condition
string id = "1"; //Here 1 is what user inputs

if (!String.IsNullOrEmpty(id))
{
    linq = linq.Where(p => p.id == id);
}

return linq.ToList(); // or whatever you want to do with it at this point

答案 1 :(得分:1)

您可能希望查看动态linq或根据您希望条件使用表达式树的复杂程度

您可能想尝试:

string id = "1";
string condition = "p.id == " + id;
var linq = from p in Post 
           where (condition) 
           select p;

或使用lambda:

string id = "1";
string condition = "p => p.id == " + id;
var linq = Post.Where(condition).SingleOrDefault();

请参阅以下内容:

Scott Gu's post on Dynamic Linq

Querying Entity with LINQ using Dyanmic Field Name

Basics of Linq Expression Trees