2012-12-03 49 views
1

这是我如何检查我的字典occurences是否已经包含一个键和一个值并为其分配键和值......但我需要另一个值,所以如何使用对象在这里?在vb.net的字典中使用对象

Occurences.Add(xRows.Cells(4).Value.ToString(), Object) 

不知怎的,像这样:

occurences(xRows.Cells(4).Value.ToString()) = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + <"1st object value here">) 

但是,这是我目前如何做到这一点,只有有一个键和一个值,但我需要像钥匙,它具有(值,值)的对象,类似的东西:

实际代码:

If (occurences.ContainsKey(xRows.Cells(4).Value.ToString())) Then 
    occurences(xRows.Cells(4).Value.ToString()) = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + Double.Parse(xRows.Cells(7).Value.ToString()) 
Else 
    occurences.Add(xRows.Cells(4).Value.ToString(), Double.Parse(xRows.Cells(7).Value.ToString())) 
End If 

Next 

然后,我有另一种插入代码,我需要使用对象的第二个值。

Using commm As New MySqlCommand() 
    With commm 
     .Parameters.Clear() 
     .Parameters.AddWithValue("@iBrnchCde", cmbBrnchCode.Text) 
     .Parameters.AddWithValue("@iFCode", pair.Key) 
     .Parameters.AddWithValue("@iDesc", <"2nd OBJECT VALUE HERE">) 
     .Parameters.AddWithValue("@iQty", pair.Value) 
     .CommandText = oInsertString 
     .Connection = _conn 
     .CommandType = CommandType.Text 
    End With 
    commm.ExecuteNonQuery() 
End Using 
+1

问题没有意义。 –

+2

@MitchWheat我在问如何在字典中使用对象,它的哪一部分没有意义? –

回答

2

执行以下操作:

Class CustomRowObject 
    Public Property Name() As String 
    Public Property Quantity() As Double 
    Public Property Description() As String 
End Class 


If (occurences.ContainsKey(xRows.Cells(4).Value.ToString())) Then 
    occurences(xRows.Cells(4).Value.ToString()).Quantity = Double.Parse(occurences(xRows.Cells(4).Value.ToString()).ToString()) + Double.Parse(xRows.Cells(7).Value.ToString()) 
Else 
    occurences.Add(xRows.Cells(4).Value.ToString(),New CustomRowObject With { .Name = a.Cells("ProductName").Value.ToString(),.Description = .Cells("ProductDesc").Value.ToString(), .Quantity = a.Cells("Quantity").Value.ToString()}) 
End If 

Next 

通过occurences("keynamegoeshere").Quantity然后引用它在你的SQL使用。

+0

而不是重复'xRows.Cells(4).Value.ToString()'4次,你可以将它分配给一个变量,并使用该变量代替。代码将更容易阅读! –

+0

@KreepN http://stackoverflow.com/questions/13736693/formatexception-was-unhandled-vb-net请再次提供一些帮助。 :) –

1

我不知道我完全理解你的问题,但如果我这样做,我建议一个不同的方法:

为什么不保存你的价值观一类,那么你的类添加到字典 - 或 - 创建类类型的词典:

Public myClass 
    Public Code As String 
    Public Desc as String 
    .... 
End Class 

Dim myClassInstance as New myClass 
'initialize fields 
occurences.Add(key, myClassInstance) 

要检索得到的值作为一个对象,并使用if typeof value is myclass then - 如果你选择的对象类型的字典。

如果您选择的对象,您可以存储不同的类和类型的过程,但成本是铸造。如果可能的话,制作一个你将用来避免投射的字典。

Private myDictionary as New Dictionary(Of String, myClass) 
+0

感谢您的回复,烨我现在试图这样做:D –