创建依赖于多个搜索字段的动态LINQ查询的最有效方法? [英] Most efficient way to create a dynamic LINQ query that depends on multiple search fields?

查看:54
本文介绍了创建依赖于多个搜索字段的动态LINQ查询的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Web应用程序,该应用程序根据输入的条件从数据库中检索数据. 问题是我有10个不同的搜索字段,只需要填写其中一个,其余的可以为空.

I'm creating a web application that retrieves data from the database based on the criteria entered. The problem is that I have 10 different search fields and only one of them is required to be filled, the rest can be null.

所以我有:

Textbox1
Textbox2
..
..
Textbox10

我当前的查询是:

checked = false;
if (Textbox1.Text != null)
{
   result = //query here
   checked = true;
}

if (Textbox2.Text != null)
{
    if(checked==false)
    {
       result = //new query here
       checked = true;
    } 
    else
    {

        result = results.Where(...new query to filter Textbox2 from previous 
        query)
    }
}

以此类推.

如何在一个查询中构建它,而忽略没有值的文本框?

How can I build this in one query and ignore the textboxes that don't have values?

谢谢

推荐答案

就像您在问题中提到的那样,您只需要在每一步缩小查询范围即可.

As you mentioned in your question you only need to narrow your query on each step.

var result = //query here

if (Textbox1.Text != null)
{
  result = result.Where(r=> r.x == Textbox1.Text);
}

if (Textbox2.Text != null)
{
  result = result.Where(r=> r.y == Textbox2.Text);
}
...

return result;

这篇关于创建依赖于多个搜索字段的动态LINQ查询的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆