LINQ过滤基于预览过滤器

时间:2013-08-25 06:34:08

标签: .net vb.net linq

我想使用LINQ,但这取决于几个因素

If cbo1.SelectedIndex > -1 Then
'LINQ filter
End If

If me.cbo2SelectedIndex > -1 Then
'Filtering the LINQ again with data from the first combobox...
End If

我是否必须重写整个LINQ或是否有其他方式

1 个答案:

答案 0 :(得分:2)

是的,你可以这样做。使用将由不同部分使用的IQueryable类型在顶部声明您的变量,然后根据您的逻辑选择性地应用过滤器。

Dim query = InitializeQuery() ' returns type IQueryable(Of YourCustomClass)

If cbo1.SelectedIndex > -1 Then
  'LINQ filter
  query = from x in query 
          where x.Condition1 = cbo1.SelectedValue 
          select x
End If

If me.cbo2SelectedIndex > -1 Then
  'Filtering the LINQ again with data from the first combobox...
  query = from x in query 
          where x.Condition2 = cbo2SelectedIndex.SelectedValue 
          select x
End If

query的类型始终保持不变。每个分支中唯一改变的是它的定义。