鉴于这样的课程
Public Class ItemPanel
Inherits Panel
Public Name as string
Public Quantity As Integer
End Class
这样的清单
Public li_ip As New List(Of ItemPanel)
我有一个子将帮助我点击一个按钮时将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
那么我怎样才能得到我想要的结果呢?我应该在其他地方写下什么?
答案 0 :(得分:4)
要按其中一个属性搜索list item
,可以使用List(Of T).Find Method 。在这种情况下,List由变量li_ip
引用,用于查找list item
的属性是Name
。
根据MSDN文档,Find
方法返回第一个元素,该元素与指定谓词定义的条件匹配(如果找到);否则,类型T的默认值。
ItemPanel
的T的默认值为Nothing
因为ItemPanel
是引用类型。因此,当Find
实际找到item
时,其Quantity
可以递增。 HTH
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
完整代码可能如下所示。
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
注意:也可以使用LINQ,但Find
可能更快。参见例如this answer
编辑:
以下是重构版本,其中方法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
或者LINQ
可以使用Find
的instaed,例如像这样:
Dim panel As ItemPanel = li_ip.SingleOrDefault(function(p) p.Name = panelName)