1

我有一个在 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
4

3 回答 3

0

使用扩展方法语法更容易做到这一点。我不认为将其作为一个 LINQ 语句来做是一个好主意。

您可以做的是首先仅使用表创建基本查询。我打算用 C# 来做,但翻译成 VB 并不复杂——我不想让你或我自己感到困惑!

var baseQuery = col;

现在您已经有了基本表,您可以开始根据您的条件添加 where。

if(condition1 == true)
{
    baseQuery = baseQuery.Where(this is your where condition);
}

if(condition2 == true)
{
    baseQuery = baseQuery.Where(this is another condition);
}

因此,您可以将您Where的 s 链接在一起,允许您根据条件缩小查询范围。

最后,您返回查询的结果,使用ToList. 这避免了您在条件下的代码重复,并且一切都更容易理解和维护。

于 2013-06-05T15:17:23.493 回答
0

如果您的 LINQ 查询有多个变量条件,请考虑使用Dynamic LINQ Library。它将允许您根据提供的参数预先将条件组合成一个字符串变量,然后将该变量用作 LINQ 查询的条件——这类似于 SQL Server 中的动态 SQL。

于 2013-06-05T14:34:59.947 回答
0

像这样使用 lambda exp:

Dim FnValueExists = 
      Function(v As String, a As List(Of String)) a Is Nothing OrElse 
                                                  a.Count = 0 OrElse 
                                                  a.Contains(v)

然后在您的 linq 中,只需测试如下值:

Dim res As IEnumerable(Of StatsDetails) = 
                    From x In col 
                    Where FnValueExists(x.Category, SelectedCategory) And 
                          FnValueExists(x.Brand, SelectedBrand)
                    Select x

确定是否选择项目的主要代码是lambda 表达式中的x那一a Is Nothing OrElse a.Count = 0 OrElse a.Contains(v)行。FnValueExists

在上述情况下,如果SelectedCategoryand/or SelectedBrandlist 为 Nothing 或为空 (Count=0),或包含该值,该项目仍将被选中。

所以如果用户没有选择任何类别,你可以设置SelectedCategoryNothing或只是一个空列表,因此FnValueExists(x.Category, SelectedCategory)将始终返回true。

于 2013-06-06T10:58:02.230 回答