使用多个下拉列表在c#中进行高级搜索

时间:2016-04-27 20:54:02

标签: c# database advanced-search advanced-filter

您好我正在进入一个应该拥有高级搜索过滤器的homefinder项目。它应该有3个下拉列表,用户可以从中选择租金金额,位置和性别类型,或者用户也可以不选择任何因为它具有默认值" ALL"这导致显示数据库中存储的所有房屋,但如果用户从下拉列表中选择一个或两个值,而另一个默认值为" ALL"或三者都有值,则应该导致他们的联盟。我尝试使用if语句

If (combobox1.text == "ALL" && combobox2.text == "ALL" && combobox3.text == "ALL")
{
 // shows all the homes
}
else if ( combobox1.text != "ALL" && combobox2.text == "ALL" && combobox3.text == "ALL")
{
 // say combobox1 is rent amount, shows all the homes having that rent amount
}

else if (combobox1.text == "ALL" && combobox2.text != "ALL" && combobox3.text == "ALL")
{
   // say combobox2 is gender type shows all the homes having that        gender category
   if (combox2.text == "Female")
     // all homes w "female"
   else
     // all homes w male
}

else if ( combobox1.text == "ALL" && combobox2.text == "ALL" && combobox3.text != "ALL")
{
// say combobox3 is location, shows all homes in that location
}

else if ( combobox1.text != "ALL" && combobox2.text != "ALL" && combobox3.text != "ALL")
{
}
else if ( combobox1.text != "ALL" && combobox2.text != "ALL" &&   combobox3.text == "ALL")
{
}

等等,这是我到目前为止所考虑的代码:l如何才能使它们相交。就像我选择500以下的租金和第一街的位置一样,我怎样才能找到位于第一街的租金为500的房屋?

顺便说一句,我已经知道如何展示家园了。我担心的是如何在下拉列表中找到项目的交叉点。

你的任何帮助都是适用的。谢谢

1 个答案:

答案 0 :(得分:0)

取决于您如何进行数据访问,但Linq会更容易和更清洁。假设您使用的是Linq2SQL或Entity Framework,并且在您的数据库中有一个名为Homes的表,那么如果您可以访问名为ctx的变量中的EF上下文,则可以执行以下操作(警告:Air代码,以及我将你的combobox1重命名为更有意义的东西)......

var homes = ctx.Homes;
if (cmbRentAmount.Text != "All") {
  homes = homes.Where(h => h.RentAmount == cmbRentAmount.Text);
}
// Similar for the other two combos
// ...
// Now we enumerate the query, which does the actual database access
var homesList = homes.ToList();

请注意,第一行中的homes变量是未枚举的查询,这意味着L2S / EF实际上并未查询数据库。如果用户选择了某些内容,您将浏览三个组合,修改查询。当您枚举homes时,它将执行查询,并为您提供所需的结果。

相关问题