fedeteka fedeteka - 2 months ago 20
Vb.net Question

How to check if 2 listbox have the same items collection?

I load items from a database on lstData then I make a copy of this state on another listbox called lstOriginal using this code

lstOriginal.Items.Clear()
For Each Item In lstData.Items
lstOriginal.Items.Add(Item)
Next


Then the user is available to make changes, add or delete items on lstData and when the user press UPDATE I need to know if the items collection of lstData and lstOriginal are the same.

I donĀ“t care about what changed, if there's a difference I will update the complete items collection on the data base.

So I need to know if the items collection of lstData and lstOriginal are the same.

The only way I know is make a loop like

Dim lstOriginalString as String
lstOriginalString = ""
For Each Item In lstOriginal.Items
lstOriginalString = lstOriginalString & Item
Next


Then another loop for lstData and a simple string compare, but I think there's gonna be a simpler way

Answer

You could use LINQ:

Dim isSame As Boolean = lstData.Items.Count = lstOriginal.Items.Count
If isSame Then
   Dim newItems = lstData.Items.Cast(Of String)()
   Dim originalItems = lstOriginal.Items.Cast(Of String)()
   isSame = Not newItems.Except(originalItems).Any()
End If

If you wanted to know if it's even in the same order:

isSame = newItems.SequenceEqual(originalItems)