OhSoConfused OhSoConfused - 1 year ago 69
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]'.


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
For Each item In myQuery
End Sub

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download