Checking listbox for multiple items

12padams

Well-known member
Joined
Feb 19, 2010
Messages
48
Programming Experience
Beginner
I am making a virtual crafting application (similar to that done in Minecraft)

currently I have made a test "crafting recipe" which checks if the listbox (mixbox) has 1 window, 1 door and 1 wheel. the code looks like this:

VB.NET:
If mixbox.Items.Contains("window") Then
            If mixbox.Items.Contains("door") Then
                If mixbox.Items.Contains("wheel") Then
                    If mixbox.Items.Count = 3 Then
                        mixbox.Items.Clear()
                        mixbox.Items.Add("car")
                    End If
                End If
            End If
        End If

It works but its long and doesn't look good and is a pain to type...

I want to make a method which allows me to type only 1 line of code...

Also not all recipes will have only 3 items... they will have many some up to 100 each...

Anyone got some code to simplify this...

Also I was thinking mabey have an item (such as car) as an array and then make it check if it has the items to create car ( which would be stored in the car array... for example:
VB.NET:
if listbox.items.contains(car()) then 
listbox.clear
listbox.items.add("car")
end if

Anyone able to help :) ???
 
You don't need multiple If statements. You can test all four conditions with one If statement. I'd probably test the Count first as it's the simplest:
VB.NET:
With mixbox.Items
    If .Count = 3 AndAlso .Contains("window") AndAlso .Contains("door") AndAlso .Contains("wheel") Then
        '...
    End If
End With
That said, you could also use a bit of LINQ and do something creative like this:
VB.NET:
If String.Join(",", mixbox.Items.Cast(Of String)().OrderBy(Function(s) s)) = "door,wheel,window" Then
    '...
End If
 
Back
Top