2014-10-02 9 views
0

지금과 같은 비효율적 인 일을 할 :VB.Net 배열을 통해 어떻게 루프합니까?

' Returns a collection of selected choices in a multichoice field 
Dim MyField As NS.ChoiceValues = CType(Me.Form.Fields("Field").Value, NS.ChoiceValues) 

If MyField.Choices.Item("Value 1") IsNot Nothing Then 
    ' Do stuff to database choice Value 1, which has id 100 
End If 

If MyField.Choices.Item("Value 1") Is Nothing Then 
    ' Do other stuff to database choice Value 1, which has id 100 
End If 

If MyField.Choices.Item("Value 2") IsNot Nothing Then 
    ' Do stuff to database choice Value 2, which has id 200 
End If 

If MyField.Choices.Item("Value 2") Is Nothing Then 
    ' Do other stuff to database choice Value 2, which has id 200 
End If 

... 

이것은 매우 비효율적이며, 선택의 수가 증가 값 때 읽을된다. 그래서 이것을 업데이트하려고합니다 :

Dim Field1Choices As New Dictionary(Of Integer, String) From { 
    {100, "Value 1"}, 
    {200, "Value 2"}, 
    {300, "Value 3"}, 
    {400, "Value 4"} 
    ... 
} 

For Each FieldChoice As String In Field1Choices 
    If MyField.Choices.Item(var_a) ' var_a should be "Value 1", "Value 2", etc. 
     DoStuff.WithCoice(Me.Database, "SomeTable", var_b) 'var_b should be 100, 200 etc. 
    End If 
Next 

분명히 이것은 작동하지 않습니다. 내 배열에 정수와 문자열이 모두 포함되어 있으므로 For Each FieldChoice As String In Field1Choices이 작동하지 않습니다.

var_avar_b이 배열 값의 값을 가져 오도록 Field1Choices 배열을 반복 할 수 있습니까?

+0

사전 적은 키 - 값 쌍을 포함'(정수, 문자열) KeyValuePair 각 FieldChoice에 들어 Field1Choices' 그러면 'FieldChoice.Key'와'FieldChoice.Value'와 같은 키/값을 얻을 수 있습니다. –

답변

0

사전에 각 항목은 KeyValuePair 값 재산 을 가지고 유형과 특성 로 반환됩니다.
For Each 루프에서 이터레이터의 유형을 선언 할 필요가 없습니다. 열거 형을보고 컴파일러가 올바르게 식별합니다. 이 경우 사전에는 정수 키와 문자열 값이 있습니다. 그래서 KeyValuePair 반복자는 정수 타입의 키와 사전의 모든 항목에 대한 문자열 유형의 값을 포함

Dim Field1Choices As New Dictionary(Of Integer, String) From { 
    {100, "Value 1"}, 
    {200, "Value 2"}, 
    {300, "Value 3"}, 
    {400, "Value 4"} 
} 

For Each FieldChoice In Field1Choices 
    Dim var_A = FieldChoice.Value 
    Console.WriteLine(var_A) 

    DIm var_B = FieldChoice.Key 
    Console.WriteLine(var_B) 

    'DoStuff.WithCoice(Me.Database, "SomeTable", var_B) 'var_b should be 100, 200 etc. 

Next 
관련 문제