如何使用LINQ过滤对象列表而不使用嵌套的If语句

时间:2017-04-11 08:42:23

标签: vb.net linq

我有两个LINQ查询,按过滤器顺序不同。我想避免使用嵌套的Sub CopyRange() Dim bottomD As Integer Dim ws As Worksheet For Each ws In Sheets(Array("A", "B", "C", "D")) ws.Activate bottomD = Range("E" & rows.Count).End(xlUp).Row Range("E2:G" & bottomD).Copy Sheets("Summary").Cells(rows.Count,"E").End(xlUp).Offset(1, 0) Next ws Dim r As Range Dim rows2 As Long Dim i As Long Set r = ActiveSheet.Range("A:A") rows2 = r.rows.Count For i = rows2 To 1 Step (-1) If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete Next End Sub 语句。

我目前的方法是:

If

4 个答案:

答案 0 :(得分:0)

我更喜欢在LINQ查询的Select CaseSort部分使用OrderBy语句,因为它更容易阅读:

Select Case search.Sort
    Case "Name"
        OutputList = OutputList.OrderBy(Function(x) x.Name).ToList()

    Case "-Name"
        OutputList = OutputList.OrderByDescending(Function(x) x.Name).ToList()

    Case "Date"
        OutputList = OutputList.OrderBy(Function(x) x.[Date]).ToList()

    Case "-Date"
        OutputList = OutputList.OrderByDescending(Function(x) x.[Date]).ToList()

    Case "Percent"
        OutputList = OutputList.OrderBy(Function(x) x.CompletedPercentage).ToList()

    Case "-Percent"
        OutputList = OutputList.OrderByDescending(Function(x) x.CompletedPercentage).ToList()

End Select

答案 1 :(得分:0)

如果我理解正确你只想避免嵌套if语句。 您可以通过使用函数实现此操作,并在条件有效时将函数保留为Return。

Function GetUserNames(userList As List(Of UserList), username As String)
    If (userList Is Nothing OrElse Not userList.Any()) Then
        Return New List(Of String)
    End If

    If Filter() Then
        Return From u In userList Order By (If(u.Name = username, 1, 0)) Descending, u.Name Ascending
    End If

    Return From u In userList
           Select u.Name Distinct
           Order By Name Descending
End Function

请注意,您没有嵌套if语句,实际上您也不需要其他部分。

还可以通过构建语句来利用linq。假设应该为两个查询应用Distinct名称:

    Dim query = userList.Select(Function(u) u.Name).Distinct

    If Filter() Then
        Return query.OrderByDescending(Function(n) If(n = username, 1, 0)).ThenBy(Function(n) n)
    End If

    Return query.OrderBy(Function(n) n)

- 更新 -

赏金要求提供可信和/或官方来源的答案。'。这就是为什么我包含了Martin Fowler文章的链接,其中描述了这种设计:

https://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html

答案 2 :(得分:0)

假设我正确解释了您的代码,为什么不删除所有的If语句?

    Dim sortUsername = If(Filter(), "", username)
    users = (From u In userlist Order By If(u.name > sortUsername, 1, 0) Descending, u.name Ascending Select u.name Distinct).ToList

答案 3 :(得分:0)

您可以在LINQ中使用let关键字,并拥有一个将用于制定决策的变量。