对于每个循环,与列表中的下一个项目进行比较

问题描述 投票:1回答:3

我正在编写一个应用程序,我从数据库中提取项目的更改历史记录,并使用For Each循环将它们放在表格中。但是,我想在表格中显示每个编辑中哪些信息已更改。是否可以将每个项的变量与For Each循环中下一个循环的变量进行比较?

就像是:

For Each k As Examplemodel In Model

  'Find next item on the loop after current one somehow
   Dim nextItem = Model.Item(k+1) 'something like this

  If k.ItemsName <> nextItem.Itemsname 'if the name has changed in edit
    'show result in bold
  Else
     'show result in normal font weight
  End If

 Next

这是可能的,如果没有,那么实现这一目标的最佳方法是什么?

vb.net
3个回答
1
投票

你不能直接在foreach循环中完成它。 如果你的Model类有索引器,你可以很容易地将它转换为for循环:

If Model.Count > 1 Then
    For i as Integer = 0 to Model.Count - 2 ' Note the -2 here !!!
        Dim Item As Examplemodel = Model(i)
        Dim NextItem As Examplemodel = Model(i + 1)

        if Item.ItemsName <> NextItem.ItemsName then
            'show result in bold
        else
            'show result in normal font weight
        end if
    Next
    'show result of NextItem here, since the last item doesn't get shown in the loop
Else
    'show result of only item here
End If

如果没有,您可以使用这样的解决方法:

Dim PrevItem as Examplemodel = Nothing ' Assuming a reference type

For Each k As Examplemodel In Model

    If Not IsNothing(PrevItem) AndAlso k.ItemsName <> Prev.Itemsname 'if the name has changed in edit
        'show result (of PrevItem!!!) in bold
    Else
        'show result (of PrevItem!!!) in normal font weight
    End If
    PrevItem = k
Next

'show result (of PrevItem (currently the last item in Model) in normal font weight

0
投票

你应该使用普通for循环:

Dim numbers() As Integer = New Integer() {1, 2, 4, 8}

Sub Main()
    For index As Integer = 0 To numbers.Length - 2
        Dim currentInt As Integer = numbers(index)
        Dim nextInt As Integer = numbers(index + 1)
        Console.WriteLine(currentInt)
        Console.WriteLine(nextInt)
    Next
End Sub

0
投票

另一种使用LINQ Aggregate扩展方法的方法,它使用第一项集合作为初始值。因此,每个项目都可以访问上一个项目。

Public Class ItemChanges
    Public Property Item As ExampleModel
    Public Property Changes As New Hash(Of String)
End Class

Public Function Check(previous As ItemChanges, current As ItemChanges) As ItemChanges
    If current.Item.Name <> previous.Item.Name Then 
        current.Changes.Add(Nameof(current.Name))
    End
    Return current
End Function

' assume model is collection of items
Dim itemWithChanges = 
    model.Select(Function(m) New ItemChanges With { .Item = m })
         .Aggregate(AddressOf(Check))
         .ToList()

然后,您可以根据需要使用计算结果 - 每个项目都将具有已更改的属性名称的哈希值

If checkedItem.Changes.Contains(Nameof(checkedItem.Item.Name)) Then
    ' use bold font or different color
End
© www.soinside.com 2019 - 2024. All rights reserved.