性别LINQ查询过滤

时间:2018-12-06 14:09:39

标签: vb.net

所以最近我正在学习Visual Basic中的LINQ查询,我有一个问题,要求我使用组合框使用给定的三个选项(男,女和全部)过滤性别。我设法做到了这样:

    If cboGender.Text = "All" Then
        rs = From cust In db.Customers
             Where cust.Name.Contains(txtName.Text)
             Select cust
    Else
        rs = From cust In db.Customers
             Where cust.Name.Contains(txtName.Text) And cust.Gender = cboGender.Text
             Select cust
    End If

但是我想知道是否有更有效的书写方式,也许不使用If语句?我有任何建议,谢谢您的帮助

2 个答案:

答案 0 :(得分:2)

使用rs作为IQueryable,您可以消除if语句的整个分支

 rs = From cust In db.Customers
      Where cust.Name.Contains(txtName.Text)
      Select cust 

If cboGender.Text != "All" Then
     rs = rs Where cust.Gender = cboGender.Text Select cust
End If

如果这是C# 然后

rs = cboGender.Text != "All" ?  rs Where cust.Gender = cboGender.Text  Select cust : rs ;

答案 1 :(得分:1)

也许更具可读性:

   rs = From cust In db.Customers
         Where cust.Name.Contains(txtName.Text) AndAlso 
               (cust.Gender = cboGender.Text OrElse cboGender.Text = "All")
         Select cust