【问题标题】:How to make cumulative search with LINQ如何使用 LINQ 进行累积搜索
【发布时间】:2013-06-13 14:10:45
【问题描述】:

如果我想通过req_ser ,req_year .. ,so on fields搜索

我执行以下操作:

            if (obj.RequestSerial != 0)
            {
                if (condition != "")
                    condition = condition + " AND ";

                condition += " req_ser= " + obj.RequestSerial;
            }

            if (obj.RequestYear != 0)
            {
                if (condition != "")
                    condition = condition + " AND ";

                condition += " req_year = " + obj.RequestYear;
            }

然后在我的选择语句中,我执行以下操作:

SELECT * FROM .... WHERE ..... + condition 

如何使用与 LINQ TO SQL 实体相同的概念进行搜索?

【问题讨论】:

    标签: c# asp.net linq search linq-to-sql


    【解决方案1】:

    你可以用同样的逻辑来做......

    var query = DB.MyItems;
    
    if(conditionA != 0)
        query = query.Where(x => x.A == conditionA);
    
    if(conditionB != 0)
        query = query.Where(x => x.B == conditionB);
    
    var items = query.ToList();
    

    使用您问题中的属性,您的代码可能如下所示:

    var query = DB.MyItems;//I don't know what you table it called
    
    if(obj.RequestSerial != 0)
        query = query.Where(x => x.req_ser == obj.RequestSerial);
    
    if(obj.RequestYear != 0)
        query = query.Where(x => x.req_year== obj.RequestYear);
    
    var items = query.ToList();
    

    【讨论】:

    • 然后在我的select linq statement 中?
    • @just_name:不要使用这样的 select 语句。或者不要在语句上应用 where ,然后像我说的那样使用 Where 函数。
    • 这些语句是否进行了我想要的累积搜索?
    • 要进行选择,如果需要,您可以在末尾添加var items = query.Select(x => x.valueYouWant);var items = query.Select(x => new { ValueA = x.valueYouWantA, ValueB = x.valueYouWantB, etc. });.ToList().ToArray()
    • @just_name:我已经更新了我的答案,以包括您的特定属性可能看起来是谁
    猜你喜欢
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2020-03-16
    • 2021-03-19
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多