OhSoConfused OhSoConfused - 15 days ago 6
Vb.net Question

Trying to get a sorted list in vb.net

I have two list boxes (Available Items & Selected Items) which are populated from a database. I'm able to add and remove via buttons between these lists but, when I remove from the Selected list, the item goes to the bottom of the Available list. It does not get alphabetized. So I'm trying a Linq option.

This is the error I'm getting:

Unable to cast object of type 'System.Linq.OrderedEnumerable2[System.Object,System.Object]' to type 'System.Collections.Generic.IEnumerable1[System.Web.UI.WebControls.ListItem]'.


Code:

Imports System.Linq
'After adding the item to the list sort it
Dim myQuery As IEnumerable(Of ListItem)

myQuery = From result In Available.Items _
Select result _
Order By result.Text Ascending
'Rebuild the list
Available.Items.Clear()
For Each item In myQuery
Available.Items.Add(item)
Next
End Sub

Answer

Since the ListItemCollection returned by Items only implements IEnumerable, and not IEnumerable(Of ListItem), you should add a Cast to your query. You will also want to use ToList(), or something else that forces evaluation of the query, before you clear it, since LINQ queries are lazily evaluated, and otherwise the list will be cleared before your query is evaluated!

myQuery = (
    From result In Available.Items.Cast(Of ListItem)() _
    Select result _
    Order By result.Text Ascending
).ToList()

You may also want to turn Option Strict On to help find additional issues at compile time.

Comments