user3754205
user3754205

Reputation: 27

vb.net counting an element of an array that has 4 possibilities

I have an array of 18 questions. Each question has 4 possibilities of answer ranging from 1 to 4. I'd like to count how many people answered question1 and so on. My codes below. Do you have a better way to do it? I can't list all 18 questions like that.

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 

Upvotes: 0

Views: 64

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use a Lookup(Of TKey, TElement) which is similar to a dictionary apart from the fact that it returns an empty sequence if the key is not available:

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

Can be tested easily with:

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())

which outputs f.e: One: 5 Two: 6 Three: 5 Four: 2

Upvotes: 1

Related Questions