【问题标题】:How to embed string condition in linq query如何在 linq 查询中嵌入字符串条件
【发布时间】:2011-03-18 13:22:47
【问题描述】:

我想在我的 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 中执行此操作吗?

【问题讨论】:

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


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    您可能需要研究动态 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

    【讨论】:

    • 我认为表达式树对于这个来说太过分了
    • 同意,但如果 Franz 最终执行类似搜索功能的操作,用户选择要搜索的字段以及条件,那么表达式树将是答案
    • var linq = Post.Where(condition).SingleOrDefault();此行不编译它给出错误
    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2021-12-02
    相关资源
    最近更新 更多