Vb.net 如何更改类列表中的值?
像这样的课Vb.net 如何更改类列表中的值?,vb.net,list,class,Vb.net,List,Class,像这样的课 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
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_项目中,因此当按钮单击两次时,只有第一次将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
那么我怎样才能得到我想要的结果呢?我还应该写什么?要通过列表项的一个属性搜索列表项,可以使用。在这种情况下,列表由变量
li_ip
引用,用于查找列表项的属性是名称
根据MSDN文档,Find
方法返回与指定谓词定义的条件匹配的第一个元素(如果找到);否则,类型T的默认值为
T的默认值为ItemPanel
是Nothing
,因为ItemPanel
是一个引用类型。因此,当Find
实际找到项目时,其数量可以增加。嗯
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
完整的代码可能是这样的
注意:也可以使用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
或者,LINQ
可以在Find
的安装中使用,例如:
Dim panel As ItemPanel = li_ip.SingleOrDefault(function(p) p.Name = panelName)
要从列表中获取项目,此答案将有所帮助:在我看来,您需要一个字典(字符串、整数)
。您是否检查了除列表
以外的容器?是否可以添加一些文本来解释您使用该代码的原因?也许您应该首先调用查找
,并检查返回值是否为空
。现在您正在遍历列表两次(一次使用.Contains
,然后使用.Find
),这似乎是不必要的。@默认值是您完全正确!我只是想用它的构建方式来回答这个问题。但是是的,代码可以这样重构。
Dim panel As ItemPanel = li_ip.SingleOrDefault(function(p) p.Name = panelName)