我有一个在 where 子句中有多个值的 LINQ 查询。where 子句中的值来自复选框列表中的过滤选项。Checkboxlist 可以返回 Null(或例如空字符串),这意味着我不需要查询中的 where 子句,因为在 checkboxlist 上选择 none 意味着选择全部。我不知道如何编写一个可以处理它的好的 LINQ,所以我最终使用了多个 IF 语句和多个查询,如下所示。我对其进行了测试,现在在 where 子句中使用 2 个参数可以正常工作。但实际上,我需要更多参数来传递给查询,如果有很多 IF 语句来完成这项工作,它会变得很混乱。如何在一个好的 LINQ 查询中处理它?
Function FilterCol(ByVal col As List(Of ProductDetails), Optional SelectedCategory As List(Of String) = Nothing, Optional SelectedBrand As List(Of String) = Nothing) As List(Of ProductDetails)
Dim strSelectedCategory As String = String.Join(",", SelectedCategory .ToArray())
Dim strSelectedBrand As String = String.Join(",", SelectedBrand .ToArray())
If strSelectedCategory = "" And strSelectedBrand = "" Then
Return col
ElseIf strSelectedCategory = "" Then
Dim res1 As IEnumerable(Of StatsDetails) = From x In col Where strSelectedBrand.Contains(x.Brand) Select x
Return res1.ToList
ElseIf strSelectedBrand = "" Then
Dim res2 As IEnumerable(Of StatsDetails) = From x In col Where strSelectedCategory.Contains(x.Category) Select x
Return res2.ToList
Else
Dim res As IEnumerable(Of StatsDetails) = From x In col Where strSelectedCategory.Contains(x.Category) And strSelectedBrand.Contains(x.Brand) Select x
Return res.ToList
End If
End Function