I am trying to grab all unique items from a DropDownList. Is there a simple way to do this?
There's always iteration:
Dim uniqueItems As New ListItemCollection()
For Each myItem As ListItem In listitems
If Not unique.Contains(myItem) Then
unique.Add(myItem)
End If
Next
This is probably not the simplest answer in terms of runtime or code, but it is the simplest concept (for me, at least).
EDIT: Code for mat1t's solution
Dim uniqueValues As IEnumerable(Of ListItem) = DropDownList1.Items.Cast(Of ListItem)().Distinct()
DropDownList1.DataSource = uniqueValues
DropDownList1.DataBind()
Try something like this:
Dim uniqueSet As New HashSet(Of ListItem)(dropdown.Items.Cast(Of ListItem)())
This is assuming of course that you have .NET 3.5 at your disposal. The HashSet(Of T)
type is a strongly-typed collection of unique items.
If you're allowed to use LINQ in this code (from .net 3.5 and Visual Studio 2008 onwards) look at the Distinct extension method.
dropdown.Items.Cast(Of ListItem)().Distinct()
It will do all of the hard work of determining whether an item is unique behind the scenes
Hey guys i have tried all three methods described above but I keep getting returned a empty list or a list full of duplicates, i'm using a LINQ data source, so I cant alter the select statement, tried 'DISTINCT' but no luck....
Sets up the initial values for the drop down menu, works and shows lot of values
Dim context As WeldsDataContext = New WeldsDataContext()
Dim query = From BIDNumber In context.Fab_Missing_NDTs Select BIDNumber
DropDownList1.DataSource = query.ToList()
DropDownList1.DataBind()
'Should remove all none-distinct values?
Dim uniqueSet As New HashSet(Of ListItem)(DropDownList1.Items.Cast(Of ListItem)())
DropDownList1.DataSource = uniqueSet
DropDownList1.DataBind()