像这样的班级
Public Class ItemPanel
Inherits Panel
Public Name as string
Public Quantity As Integer
End Class
Run Code Online (Sandbox Code Playgroud)
像这样的清单
Public li_ip As New List(Of ItemPanel)
Run Code Online (Sandbox Code Playgroud)
我有一个子菜单可以帮助我在单击按钮时将ItemPanel添加到li_ip列表中,单击的每个按钮也会将其文本添加到li_item中,因此,当按钮单击两次时,只有第一次将ItemPanel添加到li_ip中,第二次单击只会更改ItemPanel中的数量
Private Sub RefreshOrdered(sender As Object)
If Not li_item.Contains(sender.Text) Then
Dim pn As ItemPanel
With pn
.Name = sender.Text
.Quantity = 1
End With
li_ip.Add(pn)
Else
'Here I want to change the quantity in ItemPanel depend on the sender.Text
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
那么如何获得想要的结果?我还要写些什么?
要list item通过其属性之一搜索,可以使用List(Of?T).Find方法。在这种情况下,列表由变量引用,li_ip并且用于查找的属性list item为Name。
根据MSDN文档,如果找到,该Find方法将返回与指定谓词定义的条件相匹配的第一个元素;否则,该方法将返回第一个元素。否则为类型T的默认值。
的T默认值,它是ItemPanel是Nothingbecasue ItemPanel是引用类型。因此,当Find实际找到时,可以将item其Quantity递增。高温超导
Dim itm As ItemPanel = li_ip.Find(function(c) c.Name = sender.Text)
If Not itm Is Nothing Then
itm.Quantity = itm.Quantity + 1
End If
Run Code Online (Sandbox Code Playgroud)
完整的代码可能如下所示。
Private Sub RefreshOrdered(sender As Object)
' Notice that Contains like this won't work:
If Not li_ip.Contains(sender.Text) Then
Dim pn As ItemPanel
' shouldn't here the New keyword be used?
' pn = New ItemPanel()
With pn
.Name = sender.Text
.Quantity = 1
End With
li_ip.Add(pn)
Else
'Here I want to change the quantity in ItemPanel depend on the sender.Text
Dim itm As ItemPanel = li_ip.Find(function(c) c.Name = sender.Text)
If Not itm Is Nothing Then
itm.Quantity = itm.Quantity + 1
End If
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
注意:也可以使用LINQ,但可能Find更快。参见例如这个答案。
编辑:
这是重构版本,在该版本中,该方法只Find被调用一次,就像@Default提到的那样。
Private Sub RefreshOrdered(sender As Object)
Dim panelName As string = sender.Text
Dim panel As ItemPanel = li_ip.Find(function(p) p.Name = panelName)
If Not panel Is Nothing Then
' Panel with given name exists already in list, increment Quantity
panel.Quantity += 1
Else
' Panel with such name doesn't exist in list yet, add new one with this name
Dim newPanel As ItemPanel
newPanel = New ItemPanel()
With newPanel
.Name = panelName
.Quantity = 1
End With
li_ip.Add(newPanel)
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
可替换地LINQ,可以使用instaed的Find,例如是这样的:
Dim panel As ItemPanel = li_ip.SingleOrDefault(function(p) p.Name = panelName)
Run Code Online (Sandbox Code Playgroud)