vb.net计算具有4种可能性的数组元素

时间:2014-09-23 14:44:14

标签: vb.net

我有一系列18个问题。每个问题都有4种可能的答案,范围从1到4.我想知道有多少人回答了问题1,依此类推。我的代码如下。你有更好的方法吗?我无法列出所有这18个问题。

Dim question(18) as string 
Dim ans1Arr() As String = {0, 0, 0, 0}
Dim ans2Arr() As String = {0, 0, 0, 0}

    If ques(0) = 1 Then
        ans1Arr(0) = ans1Arr(0) + 1
    ElseIf ques(0) = 2 Then
        ans1Arr(1) = ans1Arr(1) + 1
    ElseIf ques(0) = 3 Then
        ans1Arr(2) = ans1Arr(2) + 1
    ElseIf ques(0) = 4 Then
        ans1Arr(3) = ans1Arr(3) + 1
    End If

    If ques(1) = 1 Then
        ans2Arr(0) = ans2Arr(0) + 1
    ElseIf ques(1) = 2 Then
        ans2Arr(1) = ans2Arr(1) + 1
    ElseIf ques(1) = 3 Then
        ans2Arr(2) = ans2Arr(2) + 1
    ElseIf ques(1) = 4 Then
        ans2Arr(3) = ans1Arr(3) + 1
    End If 

1 个答案:

答案 0 :(得分:1)

您可以使用类似于字典的Lookup(Of TKey, TElement),但如果密钥不可用则会返回空序列:

Dim lookup = question.ToLookup(Function(qNum) qNum)
Dim countAnswerOne As Int32 = lookup(1).Count()
Dim countAnswerTwo As Int32 = lookup(2).Count()
' ... '

可以通过以下方式轻松测试:

Dim question(18) As Int32
Dim rnd As New Random()
For i As Int32 = 0 To 17
    question(i) = rnd.Next(1, 5)
Next
Dim lookup = question.ToLookup(Function(qNum) qNum)

Console.Write("One: {0} Two: {1} Three: {2} Four: {3}", 
    lookup(1).Count(), lookup(2).Count(), lookup(3).Count(), lookup(4).Count())

输出f.e:One: 5 Two: 6 Three: 5 Four: 2